58 lines
1.6 KiB
C#
58 lines
1.6 KiB
C#
using ApiEfCoreLibrary.DTO.Loan.Request;
|
|
using ApiEfCoreLibrary.DTO.Loan.Response;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace ApiEfCoreLibrary.Endpoints.Loan;
|
|
using FastEndpoints;
|
|
|
|
public class CreateLoanEndpoint(LibraryDbContext database) : Endpoint<CreateLoanDto, GetLoanDto>
|
|
{
|
|
public override void Configure()
|
|
{
|
|
Post("/api/loans");
|
|
Roles("admin", "librarian");
|
|
}
|
|
|
|
public override async Task HandleAsync(CreateLoanDto req, CancellationToken ct)
|
|
{
|
|
Models.Book? bookExists = await database.Books.FirstOrDefaultAsync(a => a.Id == req.BookId, ct);
|
|
|
|
if (bookExists == null)
|
|
{
|
|
await Send.NoContentAsync(ct);
|
|
return;
|
|
}
|
|
|
|
Models.User? userExists = await database.Users.FirstOrDefaultAsync(a => a.Id == req.UserId, ct);
|
|
|
|
if (userExists == null)
|
|
{
|
|
await Send.NoContentAsync(ct);
|
|
return;
|
|
}
|
|
|
|
Models.Loan loan = new Models.Loan()
|
|
{
|
|
BookId = req.BookId,
|
|
UserId = req.UserId,
|
|
Date = req.Date,
|
|
PlannedReturningDate = req.Date.AddMonths(2)
|
|
};
|
|
|
|
database.Loans.Add(loan);
|
|
|
|
await database.SaveChangesAsync(ct);
|
|
// Pour renvoyer une erreur : Send.StringAsync("Le message d'erreur", 400);
|
|
|
|
GetLoanDto responseDto = new()
|
|
{
|
|
Id = loan.Id,
|
|
BookId = loan.BookId,
|
|
UserId = loan.UserId,
|
|
Date = loan.Date,
|
|
PlannedReturningDate = loan.PlannedReturningDate
|
|
};
|
|
|
|
await Send.OkAsync(responseDto, ct);
|
|
}
|
|
} |