Repository navigation
Expand file tree
/
Copy pathCreateBook.cs
More file actions
58 lines (49 loc) · 1.56 KB
/
Copy pathCreateBook.cs
File metadata and controls
58 lines (49 loc) · 1.56 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
using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using ModEndpoints;
using ModEndpoints.Core;
using ShowcaseWebApi.Data;
using ShowcaseWebApi.Features.Books.Configuration;
using ShowcaseWebApi.Features.Books.Data;
namespace ShowcaseWebApi.Features.Books;
public record CreateBookRequest([FromBody] CreateBookRequestBody Body);
public record CreateBookRequestBody(string Title, string Author, decimal Price);
public record CreateBookResponse(Guid Id);
internal class CreateBookRequestValidator : AbstractValidator<CreateBookRequest>
{
public CreateBookRequestValidator()
{
RuleFor(x => x.Body.Title).NotEmpty();
RuleFor(x => x.Body.Author).NotEmpty();
RuleFor(x => x.Body.Price).GreaterThan(0);
}
}
[MapToGroup<BooksV1RouteGroup>()]
internal class CreateBook(ServiceDbContext db)
: WebResultEndpoint<CreateBookRequest, CreateBookResponse>
{
protected override void Configure(
EndpointConfigurationBuilder builder,
EndpointConfigurationContext configurationContext)
{
builder.MapPost("/")
.Produces<CreateBookResponse>(StatusCodes.Status201Created);
}
protected override async Task<WebResult<CreateBookResponse>> HandleAsync(
CreateBookRequest req,
CancellationToken ct)
{
var book = new BookEntity()
{
Title = req.Body.Title,
Author = req.Body.Author,
Price = req.Body.Price
};
db.Books.Add(book);
await db.SaveChangesAsync(ct);
return WebResults.WithLocationRouteOnSuccess(
new CreateBookResponse(book.Id),
typeof(GetBookById).FullName,
new { id = book.Id });
}
}