Live notifications
Marblism integrates natively live notifications. Everytime an entity is created on your app, it will send a notification to the creator of the entity. You can customise the way notification are sent to make it work for your use cases.
![](/img/docs/frontend/notifications.png)
How to use it
Let's say you are creating a chat app and you want to notify the user receiving a message.
1. Emit a notification event
We are going to change the MessageController create
endpoint so that for every message created, we send a notification from the back-end to the front-end to the user that shall receive it.
- Import
EventService
in theMessageController
import { EventService } from 'libraries/event'
- Register
EventService
in the constructor
constructor(
private eventService: EventService,
) {}
- Emit the event after a message is created
async create(@Body() body: MessageCreateDto) {
const item = await this.messageDomainFacade.create(body)
await this.eventService.emit<{ id: string; message: string }>(
'message.created',
{ userId: item.receiverId, message: item.message },
)
return item
}
2. Hande a notification event to create a new notification
In api/src/modules/notification/infrastructure/subscribers
you will find one subscriber file per entity in your database.
notification.message.subscriber.ts
@OnEvent(
'message.created'
)
async handleCreation(
data: {userId: string, message: string},
) {
const values: Partial<Notification> = {
title: 'New message',
message: `You just received a new message: ${message}`,
senderName: 'API',
}
await this.notificationDomainFacade.create({ ...values, userId })
}
3. Send a socket event to the front-end
Add a line to push the notification live to the user using WebSocket.
notification.message.subscriber.ts
this.socketService.send(userId, 'notification.created', notification)
The front-end automatically listen to socket events sent with the key notification.created
and display the notification in real-time