Links

Managing Internal State Example

In this example, we are creating an app that records the number of messages sent on the server using the Persistence object.
To store the message count, we can write an executePostMessageSent event handler as shown below:
1
public async executePostMessageSent(message: IMessage, read: IRead, http: IHttp, persistence: IPersistence, modify: IModify): Promise<void> {
2
//create a new association to count messages
3
const association = new RocketChatAssociationRecord(RocketChatAssociationModel.MISC, 'message-count');
4
const persis = read.getPersistenceReader();
5
6
try {
7
let count = 0;
8
const record = await persis.readByAssociation(association);
9
if (record?.count) count = record.count;
10
11
await persistence.createWithAssociation({ count: ++count || 0 }, association);
12
//log the number of messages
13
console.log(`Message Sent Count: ${ count }`)
14
} catch (err) {
15
return this.getLogger().error(err);
16
}
17
}
Here,
  • The internal state is count but not the count variable whose data is stored in the memory. We use the temporary variable count to store the number of messages sent and retrieve this number from the persistence storage.
  • Every time the handler executePostMessageSent is called, we increase the count by one and then store it back to the persistence storage.
In this way, even in a cluster environment, your app in each Rocket.Chat instance can share data from a single data source, the Rocket.Chat persistence storage and maintain data consistency.
Last modified 2mo ago
Rocket.Chat versions receive support for six months after release.