Files
Heimdall/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs
T

37 lines
1.5 KiB
C#
Raw Normal View History

using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Events.Commands.CreateEvent;
#pragma warning disable CA1711
public class CreateEventHandler : IRequestHandler<CreateEventCommand, ServiceResult<CameraEventResponse>>
#pragma warning restore CA1711
{
private readonly IApplicationDbContext _context;
public CreateEventHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult<CameraEventResponse>> Handle(CreateEventCommand request, CancellationToken ct)
{
var camera = await _context.Cameras.FindAsync([request.CameraId], ct);
if (camera is null)
return ServiceResult<CameraEventResponse>.NotFound("Camera not found");
var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, request.OccurredAt);
if (request.Label is not null || request.MetadataJson is not null)
ev.SetMetadata(request.Label, request.MetadataJson);
_context.CameraEvents.Add(ev);
await _context.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<CameraEventResponse>.Success(MapResponse(ev));
}
private static CameraEventResponse MapResponse(CameraEvent e) => new(
e.Id, e.CameraId, e.Camera.SiteId, e.AgentId, e.Type, e.Confidence,
e.Label, e.SnapshotUrl, e.SnapshotThumbUrl,
e.MetadataJson, e.OccurredAt, e.CreatedAt);
}