mobxjs/mobx-state-tree

REST - create data with server side ID

exinferis opened this issue · 2 comments

Bug report

  • I've checked documentation and searched for existing issues and discussions
  • I've made sure my project is based on the latest MST version

Describe the expected behavior

I have a standard REST pattern for my application, meaning that data is created on the client side, sent via POST request to the server, then stored and sent back by the server with the generated id.

So my NOTES for example { title: string, message: string, date: string } obviously become { id: number, title: string, message: string, date: string } after creation. This is fairly standard for every web application I know.
It seems to be nearly impossible to achieve in MST when using identifier oder identifierNumber though, since those are not optional and immutable which renders it impossible to use this standard pattern. All other issues regarding this behavior were inconclusive or closed.
What is the approach in MST to use a standard REST interface when creating new data sets?

Hey @exinferis - thanks for filing this issue. I agree this can be a little fiddly with MST. At a high level, I think you can smooth things over by thinking about two distinct models in your MST codebase:

  1. The ViewModel, which models the state of your application, but does not need to have full parity with your server state or database modeling
  2. Individual models that do duplicate your server-side modeling, but can be passed around and handled by the ViewModel.

These two things can interact with one another, and you can model this whole flow through the ViewModel itself, but also handle actual server alongside.

Here's how I would do this in my own app:

import { types, getSnapshot, SnapshotOut, SnapshotIn } from "mobx-state-tree";

const Note = types.model("Note", {
  id: types.identifierNumber,
  title: types.string,
  message: types.string,
  date: types.string,
});

interface NoteSnapshot extends SnapshotIn<typeof Note> {}

type FormData = Omit<NoteSnapshot, "id">;

const FormViewModel = types
  .model("FormViewModel", {
    note: types.maybe(Note),
    title: types.maybe(types.string),
    message: types.maybe(types.string),
    date: types.maybe(types.string),
  })
  .views((self) => ({
    get formData(): FormData {
      const { title, message, date } = self;

      if (!title || !message || !date) {
        throw new Error("Missing required fields");
      }

      return { title, message, date };
    },
  }))
  .actions((self) => ({
    createNote(id: number) {
      const { formData } = self;
      const note = Note.create({
        ...formData,
        id,
      });

      self.note = note;
    },
  }));

let counter = 0;
async function server(snapshot: FormData): Promise<number> {
  console.log("Received input", snapshot);
  // Return an auto-incrementing integer as ID
  counter += 1;
  return counter;
}

(async () => {
  // Instantiate the view model of your form. In practice, this would be part of a UI or other process
  const noteForm = FormViewModel.create({
    title: "Hello from MST",
    message: "Hopefully this helps",
    date: "2024-02-15",
  });

  // Send to the server and get an id
  const id = await server(noteForm.formData);

  noteForm.createNote(id);

  const finalSnapshot = getSnapshot(noteForm);

  console.log(JSON.stringify(finalSnapshot, null, 2));
})();

You can work with this code, fork it, etc. in CodeSandbox.

Here's my thought process in designing this:

  1. Design a Note model, which mirrors the server/database schema (as an aside, we do have a date primitive if you need one, but I also sometimes just use ISO 8601 strings for dates as well.
  2. Define a NoteSnapshot interface based on the snapshot types of the Note model.
  3. Then define a utility type from that interface, which Omits the id, because we don't know it on the client yet.
  4. Then, define a separate model type. I made an assumption that you've got users filling out some kind of form for notes. You don't have to map this to a UI like a form. You could do this in-memory, in some background process in your app as well. For now, let's stick with the form idea here.
  5. FormViewModel knows about four things. It knows about the the Note model type, and it has one (you could do an array, a map, something else if you need to hold many). It also knows about the title, message, and date. Notice I typed these with maybe - so you could use this as a controlled input with some kind of HTML form where the value might be undefined.
  6. Since the view models data could be undefined, but the server model has no optionality in its title/message/date field, we also have a formData view, which is where we can do some client-side validation of the inputs if need be. You could even transform things here - this is great for when you have something like, a form that wants users to input dollars, but your server takes data as integers of cents.
  7. Optional: I threw a rudimentary error if data was missing, but this is a place you could do more interesting error handling
  8. The FormViewModel also knows how to instantiate its child Note instance: all it needs is the id (which it gets elsewhere, i.e. the server), and then it grabs its own current formData and sets the combination as its own note child.
  9. We wire up the server to expect the return type of FormViewModel's formData view and return an id
  10. After we successfully get an id, we tell the viewModel to create its note.
  11. To demonstrate the result, I've logged out the final snapshot of the ViewModel.

Let me know if that resolves your issue or not. Happy to talk further, but this is how I'd approach it. I'm sorry we don't have a ton of best practice guides for stuff like this.

Hey @exinferis - since I haven't heard back from you in a while, I'm going to convert this issue to a discussion and mark my answer as the correct one. That will close out the issue, and make it easier for folks to find this as an example if they need something similar. And of course, if my answer was insufficient, you can let me know and we can iterate in the discussions. Thanks!