using F9WebAiTest.Application.Common.Exceptions;
using F9WebAiTest.Domain.Enums.SYS.RBAC;
using F9WebAiTest.Domain.Interfaces.SYS.RBAC.Roles;
using MediatR;
namespace F9WebAiTest.Application.CQRS.SYS.RBAC.Roles.Commands;
/// 命令定义
public record RolePermission_RemoveCommand(long Id, Resource_Type_Enum ResourceType) : IRequest;
/// 命令处理器
public class RemoveRolePermissionCommandHandler(
IRoleWriteRepository roleRepository,
IRolePermissionWriteRepository rolePermissionWriteRepository,
IPublisher eventBus) : IRequestHandler
{
public async Task Handle(RolePermission_RemoveCommand command, CancellationToken cancellationToken)
{
if (command.Id <= 0) throw new F9OperationException("角色权限ID不能为空");
var rolePermission = await rolePermissionWriteRepository.GetByIdAsync(command.Id);
if (rolePermission == null) throw new F9NotFoundException("角色权限", command.Id);
var role = await roleRepository.GetByIdAsync(rolePermission.RoleId);
role.RemovePermission(rolePermission.PermissionId, command.ResourceType);
var result = await rolePermissionWriteRepository.RemoveAsync(command.Id);
if (result == false) throw new F9OperationException("权限", "解绑");
// 发布领域事件
foreach (var domainEvent in role.DomainEvents)
await eventBus.Publish(domainEvent, cancellationToken);
role.ClearDomainEvents();
return true;
}
}