We'll add a new class to the .Models project called MessageParams.cs.
This will hold paging information about our messages as well as the MessageContainer - whether it is an 'Inbox', 'Outbox', or 'Unread'. We'll set them to 'Unread' as default.
As we work through this, we'll have to be careful with the UserId.
If the MessageContainer is 'Unread' - we're requesting messages for the recipient so the UserId will equal the RecipientId.
If the MessageContaineris 'Outbox' - we'll match the UserId with the SenderId.
First, we'll update the method signature in the IMessageService() interface. Before, we didn't have the MessageParams class we needed for the parameter:
Next, in MessageService.cs - we'll implement the GetMessagesForUser() method:
There is a lot going on in this method. We'll try to break it down again.
We're querying the database for messages. We need to include both the recipient and the photos for each of them.
A switch statement to check what the values for the message parameters being passed are.
If it's 'Inbox' - we grab the messages matching where the UserId matches the recipient Id and where the recipient hasn't deleted them.
If it's 'Outbox' - we grab the messages matching where the UserId matches the sender Id and where the sender hasn't deleted them.
If it's the default ('Unread') - we grab the messages matching where the UserId matches the recipient Id, where the recipient hasn't deleted them, and where the IsRead property is false.
We're shaping the messages into a MessageToReturn DTO. If we didn't do that - then all of the information about the Users and the Photos would be included in what we send back. That's far too much to send back - and, while these mappings can be a bit of a headache (particularly to grab the photo Urls) - it's less of a headache to do it once here than have to handle it in Angular on the frontend.
Finally, we return a PagedList of MessageToReturns.
Add GetMessagesForUser() Controller Method
In MessagesController.cs - we'll add a new GET method called GetMessagesForUser:
Testing in Postman
Now, let's test in Postman. You may need to check your database if you don't remember what messages you've already sent - you can can practice in Postman and send some more.
Since I already have a token for the sender of the last message - I'll start out by getting the Outbox for that User by sending a GET request to: