| 1 | using ChapterX.Application.Chapter.Commands;
|
|---|
| 2 | using ChapterX.Application.Chapter.Queries;
|
|---|
| 3 | using MediatR;
|
|---|
| 4 | using Microsoft.AspNetCore.Authorization;
|
|---|
| 5 | using Microsoft.AspNetCore.Mvc;
|
|---|
| 6 | using Microsoft.Extensions.Logging;
|
|---|
| 7 |
|
|---|
| 8 | namespace ChapterX.API.Controllers
|
|---|
| 9 | {
|
|---|
| 10 | [Route("api/[controller]")]
|
|---|
| 11 | [ApiController]
|
|---|
| 12 | public class ChaptersController : ControllerBase
|
|---|
| 13 | {
|
|---|
| 14 | private readonly IMediator _mediator;
|
|---|
| 15 | private readonly ILogger<ChaptersController> _logger;
|
|---|
| 16 |
|
|---|
| 17 | public ChaptersController(IMediator mediator, ILogger<ChaptersController> logger)
|
|---|
| 18 | {
|
|---|
| 19 | _mediator = mediator;
|
|---|
| 20 | _logger = logger;
|
|---|
| 21 | }
|
|---|
| 22 |
|
|---|
| 23 | [HttpGet]
|
|---|
| 24 | [AllowAnonymous]
|
|---|
| 25 | public async Task<ActionResult> GetAll()
|
|---|
| 26 | {
|
|---|
| 27 | _logger.LogInformation("Fetching all chapters");
|
|---|
| 28 | var response = await _mediator.Send(new GetAllRequest());
|
|---|
| 29 | return Ok(response);
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | [HttpGet("{id:int}")]
|
|---|
| 33 | [AllowAnonymous]
|
|---|
| 34 | public async Task<ActionResult> GetById(int id)
|
|---|
| 35 | {
|
|---|
| 36 | _logger.LogInformation("Fetching chapter with ID: {ChapterId}", id);
|
|---|
| 37 | var response = await _mediator.Send(new GetRequest(id));
|
|---|
| 38 | return Ok(response);
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| 41 | [HttpPost]
|
|---|
| 42 | public async Task<ActionResult> Add([FromBody] AddRequest request)
|
|---|
| 43 | {
|
|---|
| 44 | _logger.LogInformation("Adding a new chapter with Number: {Number}", request.Number);
|
|---|
| 45 | var response = await _mediator.Send(request);
|
|---|
| 46 | return Ok(response);
|
|---|
| 47 | }
|
|---|
| 48 |
|
|---|
| 49 | [HttpPut("{id:int}")]
|
|---|
| 50 | [Authorize]
|
|---|
| 51 | public async Task<ActionResult> Update(int id, [FromBody] UpdateRequest request)
|
|---|
| 52 | {
|
|---|
| 53 | _logger.LogInformation("Updating chapter with ID: {ChapterId}", id);
|
|---|
| 54 | if (id != request.Id)
|
|---|
| 55 | {
|
|---|
| 56 | return BadRequest("Route ID and body ID must match.");
|
|---|
| 57 | }
|
|---|
| 58 |
|
|---|
| 59 | var response = await _mediator.Send(request);
|
|---|
| 60 | return Ok(response);
|
|---|
| 61 | }
|
|---|
| 62 |
|
|---|
| 63 | [HttpDelete("{id:int}")]
|
|---|
| 64 | [Authorize]
|
|---|
| 65 | public async Task<ActionResult> Delete(int id)
|
|---|
| 66 | {
|
|---|
| 67 | _logger.LogInformation("Deleting chapter with ID: {ChapterId}", id);
|
|---|
| 68 | var response = await _mediator.Send(new DeleteRequest(id));
|
|---|
| 69 | return Ok(response);
|
|---|
| 70 | }
|
|---|
| 71 | }
|
|---|
| 72 | }
|
|---|
| 73 |
|
|---|