Kashuab / mobx-depot

Scaffold MobX-powered models, queries and mutations with your GraphQL schema.
https://mobx-depot.dev
MIT License
8 stars 0 forks source link

Add helper to determine if instance was resolved from server #28

Closed Kashuab closed 1 year ago

Kashuab commented 1 year ago

It can be helpful to determine if an instance is local, or was resolved from a server response. Imagine a save method on a model that needs to decide which mutation to dispatch: create or update?

You can't just check this.id is it could throw a selection error. Base models should include the following getter that checks this:

get isExisting() {
  try { return !!this.id } catch { return false };
}

Perhaps we could abstract this behind a hasSelected method:

hasSelected(key: keyof this) {
  try { return this[key] !== undefined } catch { return false };
}

get isExisting() {
  return this.hasSelected('id') && !!this.id;
}

Another issue I see is for instances created via RootStore.create since it will generate IDs automatically. Luckily, the generated IDs look like this: __$depot_auto_id:o9cmkz7lcr so we could check for the prefix there:

get isExisting() {
  return this.hasSelected('id') && this.id && !this.id.startsWith('__$depot_auto_id');
}

I wonder if we should discourage developers from using RootStore.create to instantiate local instances, and instead construct them directly (i.e. new UserModel() instead of RootStore.create(UserModel). One should call this.store.replace(resourceFromMutation, this) anyways, so there really isn't even a need to put local models in the RootStore... perhaps that method should be made private. That's another discussion IMO.

Kashuab commented 1 year ago

Added the following to base models:

In the RootStore, you can provide the source to the resolve, create and update methods. Query and Mutation classes will automatically provide remote as the source. They will all default to local