53 lines
1.5 KiB
C#
53 lines
1.5 KiB
C#
using ApiEfCoreLibrary.DTO.Book.Request;
|
|
using ApiEfCoreLibrary.DTO.Book.Response;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace ApiEfCoreLibrary.Endpoints.Book;
|
|
using FastEndpoints;
|
|
|
|
public class CreateBookEndpoint(LibraryDbContext database) : Endpoint<CreateBookDto, GetBookDto>
|
|
{
|
|
public override void Configure()
|
|
{
|
|
Post("/books");
|
|
AllowAnonymous();
|
|
// Roles("admin");
|
|
}
|
|
|
|
public override async Task HandleAsync(CreateBookDto req, CancellationToken ct)
|
|
{
|
|
Models.Author? authorExists = await database.Authors.FirstOrDefaultAsync(a => a.Id == req.AuthorId, ct);
|
|
|
|
if (authorExists == null)
|
|
{
|
|
await Send.NoContentAsync(ct);
|
|
return;
|
|
}
|
|
|
|
Models.Book book = new Models.Book()
|
|
{
|
|
Title = req.Title,
|
|
AuthorId = req.AuthorId,
|
|
ReleaseYear = req.ReleaseYear,
|
|
Isbn = req.Isbn
|
|
};
|
|
|
|
database.Books.Add(book);
|
|
|
|
await database.SaveChangesAsync(ct);
|
|
// Pour renvoyer une erreur : Send.StringAsync("Le message d'erreur", 400);
|
|
|
|
GetBookDto responseDto = new()
|
|
{
|
|
Id = book.Id,
|
|
Title = book.Title,
|
|
BookAuthorId = book.AuthorId,
|
|
BookAuthorName = book.Author.Name,
|
|
BookAuthorFirstName = book.Author.FirstName,
|
|
ReleaseYear = book.ReleaseYear,
|
|
Isbn = book.Isbn
|
|
};
|
|
|
|
await Send.OkAsync(responseDto, ct);
|
|
}
|
|
} |