-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthorController.cs
More file actions
81 lines (67 loc) · 2.32 KB
/
AuthorController.cs
File metadata and controls
81 lines (67 loc) · 2.32 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
73
74
75
76
77
78
79
80
81
using BusinessLayer.DTOs.AuthorDTOs;
using BusinessLayer.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
namespace WebAPI.Controllers;
[Route("api/[controller]")]
[ApiController]
public class AuthorController : ControllerBase
{
private readonly IAuthorService _authorService;
private readonly IMemoryCache _memoryCache;
private readonly MemoryCacheEntryOptions _cacheEntryOptions;
public AuthorController(IAuthorService authorService, IMemoryCache memoryCache)
{
_authorService = authorService;
_memoryCache = memoryCache;
_cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(
TimeSpan.FromSeconds(10)
);
}
[HttpGet]
public async Task<ActionResult<IEnumerable<ResponseAuthorDto>>> GetAuthors(
[FromQuery] GetManyAuthorsDto getManyAuthorsDto
)
{
return Ok(await _authorService.GetAllAsync(getManyAuthorsDto));
}
[HttpGet("{id}")]
public async Task<ActionResult<ResponseDetailedAuthorDto?>> GetAuthor(int id)
{
string cacheKey = $"AuthorById_{id}";
if (!_memoryCache.TryGetValue(cacheKey, out ResponseDetailedAuthorDto? authorDto))
{
authorDto = await _authorService.GetAuthorByIdAsync(id);
if (authorDto == null)
{
return NotFound();
}
_memoryCache.Set(cacheKey, authorDto, _cacheEntryOptions);
}
return authorDto;
}
[HttpPut]
public async Task<IActionResult> PutAuthor([FromBody] UpdateAuthorDto updateAuthorDto)
{
var oldUpdatedAuthor = await _authorService.UpdateAuthorAsync(updateAuthorDto);
if (oldUpdatedAuthor == null)
return NotFound();
return Ok(oldUpdatedAuthor);
}
[HttpPost]
public async Task<ActionResult<ResponseDetailedAuthorDto>> PostAuthor(
[FromBody] AddAuthorDto addAuthorDto
)
{
var newAuthor = await _authorService.AddAuthorAsync(addAuthorDto);
return Ok(newAuthor);
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteAuthor(int id)
{
var deletedAuthor = await _authorService.DeleteAuthorByIdAsync(id);
if (deletedAuthor == null)
return NotFound();
return Ok(deletedAuthor);
}
}