10.3: Add Inbox and Outbox Service Methods
Adding MessageParams Class
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 theUserId
will equal theRecipientId
.If the
MessageContainer
is 'Outbox' - we'll match theUserId
with theSenderId
.
Implement GetMessagesForUser() Method
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
ofMessageToReturn
s.
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:
http://localhost:5000/api/users/{userId}/messages?MessageContainer=Outbox
(remember to update your UserId).
You should get back a 200 OK
response:
You can also check the headers in the response to ensure the pagination is set up correctly:
We also should be able to login and get a token for the recipient and check the Unread:
And the Inbox:
We currently aren't setting the 'isRead' property to true when a user views their message - so, for now these will be the same.
Last updated