34 lines
1.3 KiB
C#
34 lines
1.3 KiB
C#
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) : 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);
|
||
|
|
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(null, "Group.Created", "Group", group.Id.ToString()));
|
||
|
|
await _db.SaveChangesWithRetryAsync(ct: ct);
|
||
|
|
|
||
|
|
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);
|
||
|
|
}
|