Back

[Solved] WebSocket is closed before the connection is established?

  • 0
  • Web
saricden
15 Jun, 2023, 02:31

I'm receiving this error when attempting to setup a realtime connection listening for updates to a specific document in my users connection.

My code is as follows:

TypeScript
export async function addUserUpdateListener(auth_id: string, callback: (payload: RealtimeResponseEvent<unknown>) => void) {
  try {
    const userData = await db.listDocuments(
      'chat',
      'users',
      [
        // @ts-ignore
        q.equal('auth_id', [auth_id])
      ]
    );
  
    if (userData.documents.length > 0) {
      const [user] = userData.documents;
      const {$id: userDocId} = user;
      const event = `databases.chat.collections.users.documents.${userDocId}.update`;
      return client.subscribe(event, callback);
    }
  }
  catch (e) {
    console.warn(e);
  }

  return null;
}

And the path it's attempting to open a websocket connection to is: wss://cloud.appwrite.io/v1/realtime?project=648a2161cc4d4565adc2&channels%5B%5D=databases.chat.collections.messages.documents&channels%5B%5D=databases.chat.collections.users.documents.648a2228362b7d35edd2.update

Note it appears to be amalgamating the two realtime listeners I have, but I assume this is how it's meant to function.

TL;DR
The user is experiencing an error where the WebSocket connection is closing before it is established while trying to setup a realtime connection listening for updates to a specific document. The code provided subscribes to a specific event using the user's document ID, but it seems that the URL for the WebSocket connection is combining multiple realtime listeners. The user's code is written in TypeScript. A possible solution is to subscribe to the channel that includes the "update" event using the specific event format mentioned in the support thread.
saricden
15 Jun, 2023, 02:32

It's also worth noting that the other realtime listener I have setup is still working.

Binyamin
15 Jun, 2023, 02:47

Channels are a bit different from events, https://appwrite.io/docs/realtime#channels To subscribe to channel that includes the update event you need to do something like this

TypeScript
const event = `databases.chat.collections.users.documents.${userDocId}`;
return client.subscribe(event, callback);
saricden
15 Jun, 2023, 02:51

Awesome gotcha! Thanks @Binyamin πŸ˜„

saricden
15 Jun, 2023, 02:52

[Solved] WebSocket is closed before the connection is established?

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more