mirror of
https://github.com/GCMatters/hermes.git
synced 2026-02-04 05:30:13 +01:00
Usunalem EventApiController(dobry byl ale mial problemy). Dodalem EventsEndpoints, zawiera async, używa Dtos (Data Transfer Objects). Jeżeli chcecie zrobić HTTP request ale nie wiecie co dać w body JSONa to można sprawdzić w tych Dtos. EventMapping służy do zmian obiektów Dto na Entity i odwrotnie.
89 lines
2.9 KiB
C#
89 lines
2.9 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using WebApp.Data;
|
|
using WebApp.DTOs;
|
|
using WebApp.Entities;
|
|
using WebApp.Mapping;
|
|
|
|
namespace WebApp.Endpoints
|
|
{
|
|
public static class EventsEndpoints
|
|
{
|
|
const string GetEventEndpointName = "GetEvent";
|
|
|
|
public static RouteGroupBuilder MapEventsEndpoints(this WebApplication app)
|
|
{
|
|
var group = app.MapGroup("api/events")
|
|
.WithParameterValidation();
|
|
|
|
// GET /events
|
|
group.MapGet("/", async (ApplicationDbContext dbContext) =>
|
|
await dbContext.Events
|
|
.Include(Eve => Eve.Organisation)
|
|
.Select(Eve => Eve.ToEventSummaryDto()) //EventSummaryDto
|
|
.AsNoTracking()
|
|
.ToListAsync());
|
|
|
|
// GET /events/1
|
|
group.MapGet("/{id}", async (int id, ApplicationDbContext dbContext) =>
|
|
{
|
|
Event? Eve = await dbContext.Events.FindAsync(id);
|
|
|
|
|
|
return Eve is null ?
|
|
Results.NotFound() : Results.Ok(Eve.ToEventDetailsDto()); //EventDetailsDto
|
|
})
|
|
.WithName(GetEventEndpointName);
|
|
|
|
// POST /events
|
|
group.MapPost("/", async (EventCreateDto newEvent, ApplicationDbContext dbContext) =>
|
|
{
|
|
Event Eve = newEvent.ToEntity();
|
|
|
|
dbContext.Events.Add(Eve);
|
|
await dbContext.SaveChangesAsync();
|
|
|
|
return Results.CreatedAtRoute(
|
|
GetEventEndpointName,
|
|
new { id = Eve.EventId },
|
|
Eve.ToEventDetailsDto()); //EventDetailsDto
|
|
});
|
|
|
|
// PUT /events/1
|
|
group.MapPut("/{id}", async (int id, EventUpdateDto updatedEvent, ApplicationDbContext dbContext) =>
|
|
{
|
|
var existingEvent = await dbContext.Events.FindAsync(id);
|
|
|
|
if (existingEvent is null)
|
|
{
|
|
return Results.NotFound();
|
|
}
|
|
|
|
|
|
dbContext.Entry(existingEvent)
|
|
.CurrentValues
|
|
.SetValues(updatedEvent.ToEntity(id));
|
|
|
|
dbContext.Entry(existingEvent)
|
|
.Collection(Eve => Eve.EventRegistrations)
|
|
.IsModified = false;
|
|
|
|
await dbContext.SaveChangesAsync();
|
|
|
|
return Results.NoContent();
|
|
});
|
|
|
|
// DELETE /events/1
|
|
group.MapDelete("/{id}", async (int id, ApplicationDbContext dbContext) =>
|
|
{
|
|
await dbContext.Events
|
|
.Where(Eve => Eve.EventId == id)
|
|
.ExecuteDeleteAsync();
|
|
|
|
return Results.NoContent();
|
|
});
|
|
|
|
return group;
|
|
}
|
|
}
|
|
}
|