42 lines
1.2 KiB
C#
42 lines
1.2 KiB
C#
using BookHive.Models;
|
|
using BookHive.Repositories;
|
|
using BookHive.Specifications.Books;
|
|
using BookHive.Specifications.Loans;
|
|
using FastEndpoints;
|
|
|
|
namespace BookHive.Endpoints.Books;
|
|
|
|
public class DeleteBookRequest
|
|
{
|
|
public int Id { get; set; }
|
|
}
|
|
|
|
public class DeleteBookEndpoint(BookRepository bookRepository, LoanRepository loanRepository) : Endpoint<DeleteBookRequest>
|
|
{
|
|
public override void Configure()
|
|
{
|
|
Delete("/books/{@Id}", x => new { x.Id });
|
|
AllowAnonymous();
|
|
}
|
|
|
|
public override async Task HandleAsync(DeleteBookRequest req, CancellationToken ct)
|
|
{
|
|
Book? book = await bookRepository.SingleOrDefaultAsync(new GetBookByIdSpec(req.Id), ct);
|
|
|
|
if (book is null)
|
|
{
|
|
await Send.NotFoundAsync(ct);
|
|
return;
|
|
}
|
|
|
|
Loan? loan = await loanRepository.FirstOrDefaultAsync(new GetAvailableBookByIdSpec(req.Id), ct);
|
|
if (loan is not null)
|
|
{
|
|
await Send.StringAsync("Le livre est encore emprunté", 409, cancellation: ct);
|
|
return;
|
|
}
|
|
|
|
await bookRepository.DeleteAsync(book, ct);
|
|
await Send.OkAsync(cancellation: ct);
|
|
}
|
|
} |