- Print
- DarkLight
- PDF
Managing Internal State Example
- Print
- DarkLight
- PDF
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:
public async executePostMessageSent(message: IMessage, read: IRead, http: IHttp, persistence: IPersistence, modify: IModify): Promise<void> {
//create a new association to count messages
const association = new QuickMeet.ChatAssociationRecord(QuickMeet.ChatAssociationModel.MISC, 'message-count');
const persis = read.getPersistenceReader();
try {
const record = await persis.readByAssociation(association) as RecordItem[];
let count = 0;
if (record.length > 0) {
count = record[0].count;
this.getLogger().log(`Current count: ${count}`);
}
count ++;
await persistence.updateByAssociation(association, { count }, true);
//log the number of messages
this.getLogger().log(`Updated Message Sent Count: ${count}`);
} catch (err) {
this.getLogger().error(err);
}
}Here,
The
countvariable temporarily stores the number of messages sent. It is initialized to zero and updated based on data retrieved from persistent storage.When the
executePostMessageSenthandler is called, it retrieves the current message count using the readByAssociation method. If a record exists, the count variable is updated accordingly.Next, the
countis incremented by one to account for the newly sent message. Finally, the updated count is saved back to persistent storage using the updateByAssociation method, ensuring the count is preserved across different handler executions.
In this way, even in a cluster environment, your app in each QuickMeet.Chat instance can share data from a single data source, the QuickMeet.Chat persistence storage and maintain data consistency. Check the full demo for more details!