fix: validate role code uniqueness before insert
This commit is contained in:
@@ -3,6 +3,8 @@ using TakeoutSaaS.Application.Identity.Commands;
|
|||||||
using TakeoutSaaS.Application.Identity.Contracts;
|
using TakeoutSaaS.Application.Identity.Contracts;
|
||||||
using TakeoutSaaS.Domain.Identity.Entities;
|
using TakeoutSaaS.Domain.Identity.Entities;
|
||||||
using TakeoutSaaS.Domain.Identity.Repositories;
|
using TakeoutSaaS.Domain.Identity.Repositories;
|
||||||
|
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||||
|
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||||
|
|
||||||
namespace TakeoutSaaS.Application.Identity.Handlers;
|
namespace TakeoutSaaS.Application.Identity.Handlers;
|
||||||
@@ -20,20 +22,34 @@ public sealed class CreateRoleCommandHandler(
|
|||||||
// 1. 获取租户上下文
|
// 1. 获取租户上下文
|
||||||
var tenantId = request.TenantId ?? tenantProvider.GetCurrentTenantId();
|
var tenantId = request.TenantId ?? tenantProvider.GetCurrentTenantId();
|
||||||
|
|
||||||
// 2. 构建角色实体
|
// 2. 归一化输入并校验唯一
|
||||||
|
var name = request.Name?.Trim() ?? string.Empty;
|
||||||
|
var code = request.Code?.Trim() ?? string.Empty;
|
||||||
|
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(code))
|
||||||
|
{
|
||||||
|
throw new BusinessException(ErrorCodes.BadRequest, "角色名称与编码不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
var exists = await roleRepository.FindByCodeAsync(code, tenantId, cancellationToken);
|
||||||
|
if (exists is not null)
|
||||||
|
{
|
||||||
|
throw new BusinessException(ErrorCodes.Conflict, "角色编码已存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 构建角色实体
|
||||||
var role = new Role
|
var role = new Role
|
||||||
{
|
{
|
||||||
TenantId = tenantId,
|
TenantId = tenantId,
|
||||||
Name = request.Name,
|
Name = name,
|
||||||
Code = request.Code,
|
Code = code,
|
||||||
Description = request.Description
|
Description = request.Description
|
||||||
};
|
};
|
||||||
|
|
||||||
// 3. 持久化
|
// 4. 持久化
|
||||||
await roleRepository.AddAsync(role, cancellationToken);
|
await roleRepository.AddAsync(role, cancellationToken);
|
||||||
await roleRepository.SaveChangesAsync(cancellationToken);
|
await roleRepository.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
// 4. 返回 DTO
|
// 5. 返回 DTO
|
||||||
return new RoleDto
|
return new RoleDto
|
||||||
{
|
{
|
||||||
Id = role.Id,
|
Id = role.Id,
|
||||||
|
|||||||
Reference in New Issue
Block a user