logux/docs

Should clients be responsible for creating IDs for models?

Closed this issue · 5 comments

I come from a Rails/REST background, so using logux has been an educational experience for me!

I've got a quick question about how to communicate a primary ID for models between the client and server.

Say I do:

// client
client.log.add({ type: 'ADD_USER', name: 'Alice' });

// server
server.type("ADD_USER", {
  access(ctx, action, meta) {
    return true;
  },
  async process(ctx, action, meta) {
      let user = new User({ name: action.name });
      await connection.manager.save(user);
      console.log("CREATED USER WITH DATABASE ID", user.id);
      // ... how do i get `user.id` back to the client?
  }
});

My REST way of thinking says the server should return the database ID back to the client, so the client can now reference Alice by her ID.

However, since starting to use logux I'm wondering if the client should also be responsible for creating an ID for Alice, using something like a client-side guid. If I do this, is it safe to assume that the database ID is really just a private ID for the server, and not really to be used between the client and server?

Wondering if I'm thinking about this correctly.

ai commented

Yeap. It will allow client to work with Alice even before it received response from the server (useful for Optimistic UI and Offline First).

We recommend to use Nano ID as client-side ID generator.

Thanks for the question, we need to add answer to the docs.

Awesome, thanks! I'll update my code to use Nano ID.

In your apps that do client side ID creation, do you ever have logic around undoing ADD_USER if there's an ID collision? I'm wondering if thats a new state I should be coding for?

ai commented

We could think that there is 0 probability for a collision. I do not have code for this case.

Here is ID collision probability calculator.

For 1000 IDs per hour, you will have ~149 billion years needed, in order to have a 1% probability of at least one collision.

Logux has a special feature to revert changes. We created it for the cases when you have Optimistic UI and got database error or something unpredictable. If process callback throws an error, Logux Server will send logux/undo action to the client. Logux Redux will restore the latest state before ADD_USER and reduce all action actions again without ADD_USER.

Awesome, thank you!

ai commented

I will keep this issue open to not forget adding info to the docs