-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathUserController.cs
More file actions
68 lines (56 loc) · 1.76 KB
/
UserController.cs
File metadata and controls
68 lines (56 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using Microsoft.AspNetCore.Mvc;
using UserDataAPI.Models;
using UserDataAPI.Services;
namespace UserDataAPI.Controllers;
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
private readonly UserService _userService;
public UserController(UserService userService)
{
_userService = userService;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> Get()
{
var users = await _userService.GetAsync();
return Ok(users);
}
[HttpGet("{id:length(24)}")]
public async Task<ActionResult<User>> Get(string id)
{
var user = await _userService.GetAsync(id);
if (user is null)
return NotFound();
return Ok(user);
}
[HttpPost]
public async Task<ActionResult<User>> Post([FromBody] User newUser)
{
await _userService.CreateAsync(newUser);
return CreatedAtAction(nameof(Get), new { id = newUser.Id }, newUser);
}
[HttpPut("{id:length(24)}")]
public async Task<IActionResult> Put(string id, [FromBody] User updatedUser)
{
var existing = await _userService.GetAsync(id);
if (existing is null)
return NotFound();
var updated = await _userService.UpdateAsync(id, updatedUser);
if (!updated)
return StatusCode(500, "Update failed.");
return NoContent();
}
[HttpDelete("{id:length(24)}")]
public async Task<IActionResult> Delete(string id)
{
var existing = await _userService.GetAsync(id);
if (existing is null)
return NotFound();
var deleted = await _userService.RemoveAsync(id);
if (!deleted)
return StatusCode(500, "Delete failed.");
return NoContent();
}
}