---
title: "Count Number of Messages Example"
slug: "managing-internal-state-example"
updated: 2024-12-26T12:51:45Z
published: 2024-12-26T12:51:45Z
---

> ## Documentation Index
> Fetch the complete documentation index at: https://developer.rocket.chat/llms.txt
> Use this file to discover all available pages before exploring further.

# Count Number of Messages Example

In this example, we are creating an app that records the number of messages sent on the server using the **Persistence** object. All messages sent are associated with one record. The app will save the number of messages, which can be viewed from the app logs.

To store the message count, we can write an `executePostMessageSent` event handler. The app’s main class looks something like this:

```typescript
import {
    IAppAccessors,
    IConfigurationExtend,
    IEnvironmentRead,
    IHttp,
    ILogger,
    IModify,
    IPersistence,
    IRead,
} from '@rocket.chat/apps-engine/definition/accessors';
import { App } from '@rocket.chat/apps-engine/definition/App';
import { IMessage, IPostMessageSent } from '@rocket.chat/apps-engine/definition/messages';
import { IAppInfo } from '@rocket.chat/apps-engine/definition/metadata';
import { IRoom } from '@rocket.chat/apps-engine/definition/rooms';
import { RocketChatAssociationModel, RocketChatAssociationRecord } from '@rocket.chat/apps-engine/definition/metadata';
import { MessagePersistence } from './MessagePersistence';

export class PersistenceSampleApp extends App implements IPostMessageSent {
    constructor(info: IAppInfo, logger: ILogger, accessors: IAppAccessors) {
        super(info, logger, accessors);
    }
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 RocketChatAssociationRecord(RocketChatAssociationModel.MISC, 'message-count');
    const persis = read.getPersistenceReader();
    interface RecordItem {
            count: number;
        }
    
    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,

- `MISC` enumeration is used as the [association model](https://rocketchat.github.io/Rocket.Chat.Apps-engine/enums/metadata_RocketChatAssociations.RocketChatAssociationModel.html) for the number of messages.
- The `count` variable temporarily stores the number of messages sent. It is initialized to zero and updated based on data retrieved from persistent storage.
- When the `executePostMessageSent` handler is called, it retrieves the current message count using the `readByAssociation` method. If a record exists, the count variable is updated accordingly. See the [IPersistenceRead](https://rocketchat.github.io/Rocket.Chat.Apps-engine/interfaces/accessors_IPersistenceRead.IPersistenceRead.html#readByAssociation) interface for details.
- Next, the `count` is 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. See the [IPersistence](https://rocketchat.github.io/Rocket.Chat.Apps-engine/interfaces/accessors_IPersistence.IPersistence.html#updateByAssociation) interface for details.

Deploy the app to your workspace and test it by sending some messages to any channel. Then, check the app logs. The `app:executePostMessageSent` tabs show the number of messages.

![](https://cdn.us.document360.io/27ca1fd4-36d7-4cde-b4eb-97fc1652954c/Images/Documentation/image(135).png)

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.
