Exemple #1
0
        // Create new message
        public async Task <NewMessageResponse> Create(int userId, NewMessageRequest model)
        {
            // Must find sender for automapping
            var user = await _userService.GetUserWithPhotos(userId);

            model.SenderId = user.Id;
            // Check if they are matched or not
            if (await _likeService.AreMatched(model.SenderId, model.RecipientId) == false)
            {
                throw new AppException("Can not send message to an unmatched user");
            }
            if (await _context.Likes.AnyAsync(l =>
                                              l.LikerId == model.SenderId && l.Unmatched ||
                                              l.LikeeId == model.SenderId && l.Unmatched))
            {
                throw new AppException("Can not send message to an unmatched user");
            }

            if (model.Type == MessageType.Text.ToString())
            {
                model.Content = model.Content.Trim();
            }

            if (await _userService.GetUserWithPhotos(model.RecipientId) == null)
            {
                throw new KeyNotFoundException("User not found");
            }

            var message = _mapper.Map <Message>(model);

            _context.Add(message);

            if (await _context.SaveChangesAsync() > 0)
            {
                return(_mapper.Map <NewMessageResponse>(message));
            }

            throw new AppException("Send messaged failed");
        }