public async Task <IActionResult> GetLastTwentyMessages(GetMessagesDTO getMessage) { if (!ModelState.IsValid) { return(BadRequest("Bad Request")); } var messages = await _repository.GetMessageCointainer(getMessage).ConfigureAwait(true); if (messages == null) { return(NotFound("Not found any chats with requester id.")); } return(Ok(messages)); }
public async Task <IEnumerable <Message> > GetMessageCointainer(GetMessagesDTO getMessages) { IList <Message> messages = new List <Message>(); Chat chat = await _context.Chats.FirstOrDefaultAsync(x => x.Id == getMessages.ChatId && x.ChatMemberships.Any(y => y.UserId == getMessages.RequesterId)).ConfigureAwait(true); User sender = await _context.Users.FirstOrDefaultAsync(x => x.Id == getMessages.RequesterId).ConfigureAwait(true); if (chat == null || sender == null) { return(null); } var messagesToProccess = _context.Messages.Where(x => x.ChatId == getMessages.ChatId).ToList(); if (messagesToProccess == null || messagesToProccess.Count == 0) { return(messages); } if (getMessages.IdLastMessage == 0) { getMessages.IdLastMessage = messagesToProccess.LastOrDefault().Id; } int iterator = 0; var messageWithCorrectedId = messagesToProccess.Where(x => x.Id <= getMessages.IdLastMessage).ToList(); for (int i = messageWithCorrectedId.Count - 1; i >= 0; i--) { if (messageWithCorrectedId[i] == null) { break; } messages.Add(messageWithCorrectedId[i]); iterator++; if (iterator >= 20) { break; } } return(messages.Reverse()); }