Which is better approach to send push notification in Kuzzle using hooks or subscription?

Viewed 66

I’m using Kuzzle as backend for my realtime chat application. What is the better approach to sending push notification when user is offline in a mobile chat app?

1. Using custom plugin hooks

// check for every message in chat 
this.hooks = {
  'document:afterCreate': (request) => {

    if (request.input.resource.collection == 'messages') {

      let message = request.input.body;
      this.context.accessors.sdk.document.get('now', 'user_sessions', message.otherUserId).then((userSession) => {

        if (!userSession._source.isOnline) {
          userSession._source.devices.forEach(device => {
            // send push notification
          });
        }
      })
    }
  }
}

2. Subscription per user for all users after the Kuzzle server start-up

const app = new Backend('kuzzlebackend')

app.start()
  .then(async () => {
    // Application started

    // Loops through all users and adds their subscriptions to Kuzzle

    foreach(user in users) {
      app.sdk.realtime.subscribe('now', 'messages', { ‘otherUserId' : user._id }, async (notification: Notification) => {

        this.context.accessors.sdk.document.get('now', 'user_sessions', user._id).then((userSession) => {

        if (!userSession._source.isOnline) {
          userSession._source.devices.forEach(device => {
            // send push notification
          });
        }
      })
      })
    }
  })
1 Answers

You should use the hook mechanism on the generic:document:afterWrite event to send notification to offline users when a new message is created.

This event will be triggered every time a document is written with one of the Document controller action, and for the m* action family it you will able to process documents in bulk instead of one by one.

Related