mswjs / data

Data modeling and relation library for testing JavaScript applications.

Home Page:https://npm.im/@mswjs/data

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Server-Client synchronization

kettanaito opened this issue · comments

In order to use this library for SSR scenarios, there should be a way to synchronize the DB state on the server based on the operations performed on the client.

Scenario

  1. I load a page with an empty BD on the server.
  2. I load the client, it gets the payload from the server, which gets it from the server-side DB.
  3. I perform some client-side interactions, creating a new entity in the client-side DB.
  4. I reload the page. I should see the client-side DB state being delivered from the server.

This doesn't have to be an actual synchronization, given the limitations of sharing data between environments. It may be a smart client-side DB that hydrates the values from the storage (#49). That would, however, result in the SSR mismatch with the different data between the server and the client.

Option 1: WebSockets

Spawn a local WebSocket server to signal events from the db usage on the client to the server-side db usage.

Advantages

  • Real-time synchronization using an established protocol.

WebSocket is a great choice, as data updates may be bidirectional:

  • Client updated -> apply to the server.
  • Server update (i.e. Next.js API route) -> apply to the client.

Disadvantages

  • Need to spawn a server, which means having to run an extra command as a part of your work with data.
    • This can be negated, as the server may be spawned internally, without asking the user to execute any extra commands.

It would be great to spawn the WS server implicitly, never exposing it to the end-user. The server address could be mafically shared between the server- and the client-side DB instances.

Implementation

The library determines if the current environment is Node.js, and if so, creates a WebSocket server. The server listens to client-side update events and applies them to the server db instance. The server emits server-side update events to the client as well.

The client-side part of the library attempts to connect to the server. If the connection fails (no server counterpart), handle it gracefully. If the connection is established, the server and the client may be synchronized via socket events.

Observation: Next.js re-evaluates the db.js module where you create the database. This means even if the client signals to update the server-side db instance, and it updates, when the page refreshes all the server runtime is thrown away, and the db is instantiated anew.