-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthorsController.cs
More file actions
72 lines (60 loc) · 2.48 KB
/
AuthorsController.cs
File metadata and controls
72 lines (60 loc) · 2.48 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
69
70
71
72
namespace CourseLibrary.API.Entities
{
public class Author{}
}
// DTO
namespace CourseLibrary.API.Models
{
public class Author{};
}
namespace CourseLibrary.API.Controllers
{
[ApiController]
[Route("api/authors")]//[Route("api/[controller]")]
public class AuthorsController : ControllerBase
{
IAuthorRepository _repo;
IMapper _mapper;
public AuthorsController(IAuthorRepository repository, IMapper mapper)
{
_repo = repository ?? throw new System.ArgumentNullException(nameof(repository));
_mapper = mapper ?? throw new System.ArgumentNullException(nameof(mapper));
}
[HttpGet()]
[HttpHead] // Similar to get but with no response payload. Only to retrieve info in the header so lightweight.
public ActionResult<IEnumerable<Models.Author>> GetAuthors()
{
// Get the requested authors as entities from the data source
var authors = _repo.GetAuthors();
// Map them to the corresponding DTos (Models)
var result = _mapper.Map<IEnumerable<Models.Author>>(authors);
// Return with code
return Ok(result);
}
// REturns the detaul
[HttpGet("{authorId:guid}", Name = "GetAuthor")] // :syntax is to disambiguate if you have two ways of querying
public IActionResult GetAuthor(Guid authorId)
{
var authorFound = _repo.GetAuthor(authorId);
if(authorFound is null)
return NotFound();
return Ok(_mapper.Map<Models.Author>(authorFound));
}
// [HttpGet("{authorId:int")]
// public IActionResult GetAuthor(int authorId)
// {
// }
[HttpPost]
public ActionResult<Models.Author> CreateAuthor(Models.AuthorCreation author)
{
var authorEntity = _mapper.Map<Entities.Author>(author);
_repo.AddAuthor(authorEntity); // it is added to dbcontext session not the db itself
_repo.Commit(); // now it is saved to the database
var result = _mapper.Map<Models.Author>(authorEntity);
return CreatedAtRoute("GetAuthor", new { authorId = result.Id }, result);
// the <authorId> field in the anynomous object is matching with route parameter name in the GetAuthor action
// Populates the Location header with URI for where to get the created resource
// And the result is the response body
}
}
}