public async Task <Unit> Handle(EditPlayerCommand request, CancellationToken cancellationToken)
        {
            var existing = await _context.Players.FirstOrDefaultAsync(p => p.Id == request.Id, cancellationToken);

            _logger.LogInformation($"Trying to get player {request.Id.ToString()}");

            if (existing == null)
            {
                throw new NotFoundException(nameof(Player), request.Id);
            }

            await ValidateNickname();

            existing.Nickname = request.Nickname;

            _context.Players.Update(existing);

            _logger.LogInformation($"Updating player {request.Id.ToString()}");

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);

            async Task ValidateNickname()
            {
                if (!string.Equals(existing.Nickname, request.Nickname, StringComparison.OrdinalIgnoreCase))
                {
                    var isNicknameUnique = await _playersService.IsNicknameUniqueAsync(request.Nickname, request.Id);

                    _logger.LogInformation(
                        $"Checking if nickname {request.Nickname} for {request.Id.ToString()} is unique ");

                    if (!isNicknameUnique)
                    {
                        throw new EntityExistsException(nameof(Player), request.Nickname);
                    }
                }
            }
        }
Example #2
0
        public async Task <Guid> Handle(AddPlayerCommand request, CancellationToken cancellationToken)
        {
            var isUnique = await _playersService.IsNicknameUniqueAsync(request.Nickname, null);

            if (!isUnique)
            {
                throw new EntityExistsException(nameof(Player), request.Nickname);
            }

            var id = _idGenerator.NewGuid();

            var player = new Player
            {
                Id       = id,
                Nickname = request.Nickname.Trim(),
                Added    = _dateTimeService.UtcNow
            };

            await _context.Players.AddAsync(player, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);

            return(id);
        }