Files
Heimdall/src/Heimdall.Application/Groups/Commands/CreateGroup/CreateGroupCommand.cs
T

35 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.Groups.Commands.CreateGroup;
public record CreateGroupCommand(string Name, string? Description, Guid? ActorId = null) : IRequest<ServiceResult<GroupResponse>>;
public class CreateGroupCommandHandler : IRequestHandler<CreateGroupCommand, ServiceResult<GroupResponse>>
{
private readonly IApplicationDbContext _db;
public CreateGroupCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<GroupResponse>> Handle(CreateGroupCommand request, CancellationToken ct)
{
var exists = await _db.Groups.AnyAsync(g => g.Name == request.Name, ct).ConfigureAwait(false);
if (exists)
return ServiceResult<GroupResponse>.Conflict("A group with this name already exists");
var group = new Group(request.Name, request.Description);
_db.Groups.Add(group);
_db.AuditLogs.Add(new AuditLog(request.ActorId, "Group.Created", "Group", group.Id.ToString(),
newValue: System.Text.Json.JsonSerializer.Serialize(new { group.Name, group.Description })));
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
return ServiceResult<GroupResponse>.Success(Map(group, 0));
}
private static GroupResponse Map(Group g, int userCount) => new(
g.Id, g.Name, g.Description, userCount, g.CreatedAt, g.UpdatedAt);
}