How to know which shared type have been changed from update binary?

I have a YMap with different types inside it. Example representation if it would be a JSON:

{
   "item1": {
      "textItem": "Text content",
      "arrayItem": [
         "another textContent",
      ],
   },
   "item2": {
      "textItem2": "yet another text content",
   }
   ...
}

Client changes some part, eg. item1.arrayItem[0].

How do I know on the server side which part has been changed? I use Hocuspocus Server, which has hooks: Hooks – Tiptap I suppose they are similar to messages handled by WebsocketServer. For example there is an onChange hook with update object as a part of payload. I have tried to convert update object to readable one by decodeUpdate, but seems it is useless.

Or there is no way to do that, and I need to observe changes of the YMap right on the server side by creating provider the same way as on client?

The main purpose of this action that I need to save the content of the YMap converted to a readable format to my database. But I don’t want to rewrite all content, but only items changed.

As I still don’t know which part of YMap is being changed, I have a following concept:

  1. Every time a client starts to observe some Shared Type, I send awareness data, like, this client is working on this Shared Type (i.e. YMap key).
  2. On server side, once receiving awareness update I start to observe the same Shared Type. Every time client changes it, server gets Shared Type updates and saves its content to my DB.
  3. Once client disconnects or unobserves Shared Type, I send awareness data about that and unobserve that Shared Type on server side.

Is it legit or am I doing over-engineering?

To observe any changes, you have to observe the shared type. See https://docs.yjs.dev/api/shared-types/y.map#observing-changes-y.mapevent.

To do this server-side, you just need to set up the observe handler onLoad before any updates come in from the client. Don’t use Awareness for this; assume that if a Doc has been connected to by the client that it is actively being worked on. The observe handler should automatically be removed on disconnect when the server Doc is destroyed.

1 Like