first commit
This commit is contained in:
+40
@@ -0,0 +1,40 @@
|
||||
using F9WebAiTest.Application.Common.Exceptions;
|
||||
using F9WebAiTest.Application.Interfaces.SnowflakeID;
|
||||
using F9WebAiTest.Domain.Entities.SYS.RBAC;
|
||||
using F9WebAiTest.Domain.Interfaces.SYS.RBAC.Users;
|
||||
using MediatR;
|
||||
|
||||
namespace F9WebAiTest.Application.CQRS.SYS.RBAC.Users.Commands;
|
||||
|
||||
/// <summary>命令定义</summary>
|
||||
public record UserRole_AssignCommand(long UserId, long RoleId) : IRequest<long>;
|
||||
|
||||
/// <summary>命令处理器</summary>
|
||||
public class UserRole_AssignCommandHandler(
|
||||
IUserRoleWriteRepository userRoleWriteRepository,
|
||||
IUserWriteRepository userWriteRepository,
|
||||
ISnowflakeIdGenerator snowflakeIdGenerator,
|
||||
IPublisher eventBus) : IRequestHandler<UserRole_AssignCommand, long>
|
||||
{
|
||||
public async Task<long> Handle(UserRole_AssignCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
if (command.UserId <= 0) throw new F9OperationException("用户ID不能为空");
|
||||
if (command.RoleId <= 0) throw new F9OperationException("角色ID不能为空");
|
||||
|
||||
var newEntity = new UserRole(snowflakeIdGenerator.CreateId(), command.UserId, command.RoleId);
|
||||
|
||||
var user = await userWriteRepository.GetByIdAsync(command.UserId);
|
||||
if (user == null) throw new F9NotFoundException("用户", command.UserId);
|
||||
user.AddRole(newEntity.Id);
|
||||
|
||||
var result = await userRoleWriteRepository.AssignAsync(newEntity);
|
||||
if (result == false) throw new F9OperationException("权限", "绑定");
|
||||
|
||||
// 发布领域事件
|
||||
foreach (var domainEvent in user.DomainEvents)
|
||||
await eventBus.Publish(domainEvent, cancellationToken);
|
||||
user.ClearDomainEvents();
|
||||
|
||||
return newEntity.Id;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user