1

I have a question about JS Kuzzle SDK and the "reconnected" event. In my team we are looking to build a service that connects to a Kuzzle instance and needs to run "indefinitely". This means we need to handle disconnection and reconnection. We used the events to handle that but we are having trouble to make it stable. We had problems with a code which looks like this :

this.kuzzle = new Kuzzle(new WebSocket(hostname, { port: port }), { offlineMode: "auto" });

const onConnected = async () => {
  console.log('CONNECTED');
}

// This triggers correctly
this.kuzzle.addListener('connected', onConnected);
// This doesn't trigger
this.kuzzle.addListener('reconnected', onConnected);

// This triggers correctly
this.kuzzle.addListener('disconnected', () => {
    console.log('disconnected');
});

this.kuzzle.connect().catch(e => console.log('connection error'));

Is there something we're missing out in configuration? And also, is there a reconnection timeout that stops the reconnection attempts after a certain number of attempts or amount of time?

Software versions : Kuzzle: 2.17.4 kuzzle-sdk: 7.10.0

Thanks in advance!

EDIT

The problem was not coming from Kuzzle and event not triggering but from using asynchronous actions inside the callbacks. As we needed to handle the authentication in these events, the solution was right there in front of us : the authenticator property.

this.kuzzle.authenticator = async () => {
    if (!this.kuzzle.authenticated) {
        await this.kuzzle.auth.login('local', credentials);
    }
}

And it did the trick.

Bforting
  • 11
  • 2

1 Answers1

1

The SDK should automatically reconnect and resubscribe when passing the offlineMode: 'auto' options to the Kuzzle constructor.

Also, you shouldn't use these events to handle re-authentication, actually if you register an async function, awaiting stuff inside, the behavior is unpredictable since event handler are not async nor awaited.

To handle re-authentication after re-connection, you can use the Kuzzle.authenticator property to define a method that will authenticate the SDK. It can be a call to sdk.auth.login for example.

kuzzle.authenticator = async () => {
  await kuzzle.auth.login('local', { username: 'test', password: 'test' });
};

Another solution is to use an API key which is not expiring to authenticate the SDK.

Aschen
  • 1,691
  • 11
  • 15