41 lines
1.2 KiB
C#
41 lines
1.2 KiB
C#
using AutoMapper;
|
|
using FastEndpoints;
|
|
using MetaCourse.Api.Data;
|
|
using MetaCourse.Api.DTOs.Courses;
|
|
using MetaCourse.Api.Entities;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace MetaCourse.Api.Endpoints.Courses;
|
|
|
|
public class CreateCourseEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<CreateCourseDto, GetCourseDto>
|
|
{
|
|
public override void Configure()
|
|
{
|
|
Post("api/courses");
|
|
AllowAnonymous();
|
|
Summary(s => s.Summary = "Crée un nouveau cours (statut Brouillon par défaut)");
|
|
}
|
|
|
|
public override async Task HandleAsync(CreateCourseDto req, CancellationToken ct)
|
|
{
|
|
var creatorExists = await db.Users.AnyAsync(u => u.Id == req.CreatorId, ct);
|
|
if (!creatorExists)
|
|
{
|
|
AddError(r => r.CreatorId, "L'utilisateur créateur n'existe pas.");
|
|
await SendErrorsAsync(404, ct);
|
|
return;
|
|
}
|
|
|
|
var course = mapper.Map<Course>(req);
|
|
db.Courses.Add(course);
|
|
await db.SaveChangesAsync(ct);
|
|
|
|
var created = await db.Courses
|
|
.Include(c => c.Creator)
|
|
.Include(c => c.Topics)
|
|
.FirstAsync(c => c.Id == course.Id, ct);
|
|
|
|
await SendAsync(mapper.Map<GetCourseDto>(created), 201, ct);
|
|
}
|
|
}
|