The best way to send a message to the frontend when saving a ydoc to the database in y-websocket backend?

I am currently building an application centered on collaboration between lawyers. Based on tiptap and of course yjs. One of the important things about legal documents is that they are stored securely. Therefore, a message should be sent to the client that the change they made has been saved/persisted. What is the best way to do this? If I use for example ymap.set(‘updateSuccess’, ‘onCallbackHandler’) ydoc goes into an infinite loop. Any suggestions?

I send custom message over the WebSocket channel to notify the server/client.

    const encoder = encoding.createEncoder();
    encoding.writeVarUint(encoder, DOCUMENT_SAVED_ID);
    provider.ws?.send(encoding.toUint8Array(encoder));
2 Likes

Hey rich-meetingflow, yeah that was the first one I tried to do but unfortunately without success. I tried your suggestion but it didn’t work for me either. At the client it throws error in decoded.js from the yjs module. In my case it looks like this:
const encoder = encoding.createEncoder();
encoding.writeVarUint(encoder, SOME_NUMBER)
for (const conn of doc.conns) {
conn[0].send(encoding.toUint8Array(encoder))
}
I just can’t seem to figure out exactly how encoding.writeVarUint(encoder, ???) works

Thanks, @rich-meetingflow - Your code lets me suddenly understand encoding.writeVarUint(encoder, DOCUMENT_SAVED_ID);

@bazhares - Just share my experiment code which works.

Server-side

  const encoder = encoding.createEncoder();
  encoding.writeVarUint(encoder, 3);
  encoding.writeVarString(encoder, 'test message');
  const message = encoding.toUint8Array(encoder);
  doc.conns.forEach((_, conn) => {
    send(doc, conn, message, true);
  });

Client-side

    this.provider.ws.addEventListener('message', (event: any) => {
      const data = new Uint8Array(event.data);
      const decoder = decoding.createDecoder(data);
      const messageType = decoding.readVarUint(decoder);

      console.log('Message type from server::', messageType);
      if (messageType === 3) {
        console.log(
          'Message content from server::',
          decoding.readVarString(decoder)
        );
      }
    });
3 Likes