-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeleteBook.cs
46 lines (40 loc) · 1.11 KB
/
DeleteBook.cs
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
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using ModEndpoints;
using ModEndpoints.Core;
using ModResults;
using ShowcaseWebApi.Data;
using ShowcaseWebApi.Features.Books.Configuration;
namespace ShowcaseWebApi.Features.Books;
public record DeleteBookRequest(Guid Id);
internal class DeleteBookRequestValidator : AbstractValidator<DeleteBookRequest>
{
public DeleteBookRequestValidator()
{
RuleFor(x => x.Id).NotEmpty();
}
}
[MapToGroup<BooksV1RouteGroup>()]
internal class DeleteBook(ServiceDbContext db)
: WebResultEndpoint<DeleteBookRequest>
{
protected override void Configure(
IServiceProvider serviceProvider,
IRouteGroupConfigurator? parentRouteGroup)
{
MapDelete("/{Id}");
}
protected override async Task<Result> HandleAsync(
DeleteBookRequest req,
CancellationToken ct)
{
var entity = await db.Books.FirstOrDefaultAsync(b => b.Id == req.Id, ct);
if (entity is null)
{
return Result.NotFound();
}
db.Books.Remove(entity);
var deleted = await db.SaveChangesAsync(ct);
return deleted > 0 ? Result.Ok() : Result.NotFound();
}
}