Veikedo

Untitled

Dec 17th, 2020
970
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1.   public class CreateUserCommand : IRequest<ItemResponse<UserType>>
  2.   {
  3.     public CreateUserCommand(UserType user)
  4.     {
  5.       User = user;
  6.     }
  7.  
  8.     public UserType User { get; }
  9.  
  10.     public class Validator : AbstractValidator<CreateUserCommand>
  11.     {
  12.       public Validator(UserValidator userValidator)
  13.       {
  14.         CascadeMode = CascadeMode.StopOnFirstFailure;
  15.  
  16.         RuleFor(x => x.User)
  17.           .NotNull()
  18.           .SetValidator(userValidator, UserValidator.OnCreateRules)
  19.           .OverridePropertyName(string.Empty);
  20.       }
  21.     }
  22.   }
  23.  
  24.   public class UserValidator : AbstractValidator<UserType>
  25.   {
  26.     private const string OnCreate = nameof(OnCreate);
  27.     private const string OnUpdate = nameof(OnUpdate);
  28.  
  29.     public UserValidator(IUserRepository userRepository)
  30.     {
  31.       RuleFor(x => x.Email)
  32.         .NotEmpty()
  33.         .EmailAddress()
  34.         .OverridePropertyName("email");
  35.  
  36.       RuleSet(OnCreate, () =>
  37.       {
  38.         RuleFor(x => x.Email)
  39.           .MustAsync(async (email, cancel) =>
  40.           {
  41.             var tryGetUserByEmail = await userRepository.TryGetUserByEmail(email, cancel);
  42.             return tryGetUserByEmail == null;
  43.           })
  44.           .WithMessage("User with email '{PropertyValue}' already exists")
  45.           .OverridePropertyName("email");
  46.       });
  47.  
  48.       RuleSet(OnUpdate, () =>
  49.       {
  50.         RuleFor(x => x.Email)
  51.           .MustAsync(async (user, email, cancel) =>
  52.           {
  53.             var existing = await userRepository.TryGetUserByEmail(email, cancel);
  54.             return existing == null || user.Id == existing.Id;
  55.           })
  56.           .WithMessage("User with the same email already exists")
  57.           .OverridePropertyName("email");
  58.       });
  59.     }
  60.  
  61.     public static string[] OnCreateRules => new[] {"default", OnCreate};
  62.     public static string[] OnUpdateRules => new[] {"default", OnUpdate};
  63.   }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment