import { isEqual, pick } from "es-toolkit/compat"; import { action, makeObservable, observable, runInAction, toJS } from "mobx"; import type { JSONObject } from "@shared/types"; import type Store from "~/stores/base/Store"; import type { PartialExcept } from "~/types"; import Logger from "~/utils/Logger"; import { getFieldsForModel, getFieldsForModelClass } from "../decorators/Field"; import { LifecycleManager } from "../decorators/Lifecycle"; import { getRelationsForModelClass } from "../decorators/Relation"; /** * MobX records decorator annotations on the prototype under a symbol with this * description. */ const storedAnnotationsDescription = "mobx-stored-annotations"; /** * Returns the keys of every decorated member on a model, including those * inherited from base classes. The nearest record on the prototype chain * already includes the parents' annotations, so the search stops there. * * With `useDefineForClassFields: false` a field declared without an initializer * never exists on the instance, so MobX cannot annotate it. This helper, and * the pre-definition in `initialize`, can be removed if that compiler option * is enabled. * * @param target the model to inspect. * @returns the keys annotated with a MobX decorator. */ function getAnnotatedKeysForModel(target: Model): (string | symbol)[] { let prototype = Object.getPrototypeOf(target); while (prototype && prototype !== Object.prototype) { const symbol = Object.getOwnPropertySymbols(prototype).find( (candidate) => candidate.description === storedAnnotationsDescription ); if (symbol) { const annotations: Record = Reflect.get( prototype, symbol ); return Reflect.ownKeys(annotations); } prototype = Object.getPrototypeOf(prototype); } return []; } interface PendingField { /** The last value known to be accepted by the server. */ confirmed: unknown; /** The number of requests in flight that wrote to the field. */ count: number; } /** Fields on each model that have an optimistic write in flight. */ const pendingFields = new WeakMap>(); export default abstract class Model { static modelName: string; /** * Restores data written by toPersisted to the shape the model expects, * discarding any properties that are not declared fields. Records written by * a different version of the app may not match the current model. * * @param record the persisted representation of a model. * @returns the data to construct or update a model with. */ static fromPersisted( record: Record ): PartialExcept { const fields = getFieldsForModelClass(this); return JSON.parse(JSON.stringify(pick(record, ["id", ...fields]))); } @observable id: string; @observable isSaving = false; @observable isNew = false; @observable createdAt: string; @observable updatedAt: string; store: Store; constructor(_fields: Record, store: Store) { this.store = store; } /** * Applies the initial data and makes the instance observable. * * Call this from the constructor of the most-derived class. MobX can only * annotate fields that already exist on the instance, and a subclass's fields * do not exist until its own constructor has run. * * @param fields the data to construct the model with. */ protected initialize(fields: Record) { const declared = [ ...getFieldsForModel(this), ...getAnnotatedKeysForModel(this), ]; for (const field of declared) { if (field in this) { continue; } Object.defineProperty(this, field, { configurable: true, enumerable: true, value: undefined, writable: true, }); } this.updateData(fields); this.isNew = !this.id; makeObservable(this); this.initialized = true; } /** * Ensures all the defined relations and policies for the model are in memory. * * @returns A promise that resolves when loading is complete. */ async loadRelations( this: Model, options: { withoutPolicies?: boolean } = {} ): Promise { return this.store.relationFetches.run(this.id, () => { const promises = []; const relations = getRelationsForModelClass( this.constructor as typeof Model ); if (relations) { for (const properties of relations.values()) { const store = this.store.rootStore.getStoreForModelName( properties.relationClassResolver().modelName ); if ("canFetchById" in store && store.canFetchById) { const id = this[properties.idKey]; if (id) { promises.push(store.fetch(id as string)); } } } } const policy = this.store.rootStore.policies.get(this.id); if (!policy && !options.withoutPolicies && this.store.canFetchById) { promises.push(this.store.fetch(this.id, { force: true })); } return Promise.all(promises); }); } /** * Persists the model to the server API. * * Fields passed as params are applied optimistically, and reverted if the * request fails. * * @param params Specific fields to save, if not provided the model will be serialized * @param options Options to pass to the store * @returns A promise that resolves with the updated model * @throws The original error if the request fails. */ save = async ( params?: Record, options?: Record ): Promise => { const isNew = this.isNew; this.isSaving = true; let settle: ((success: boolean) => void) | undefined; try { if (isNew) { LifecycleManager.executeHooks(this.constructor, "beforeCreate", this); } else { LifecycleManager.executeHooks(this.constructor, "beforeUpdate", this); } if (params) { settle = this.applyOptimistic(params); } else { params = this.toAPI(); } const model = await this.store.save( { ...params, // ensure that the id is passed if the document has one id: this.id, }, { ...options, isNew, } ); // if saving is successful set the new values on the model itself this.updateData(Object.assign({}, params, model)); settle?.(true); if (isNew) { LifecycleManager.executeHooks(this.constructor, "afterCreate", this); } else { LifecycleManager.executeHooks(this.constructor, "afterUpdate", this); } return model; } catch (err) { settle?.(false); throw err; } finally { this.isSaving = false; } }; /** * Sets declared fields on the model ahead of a request to the server, so * that observers update without waiting for the response. * * @param params the values being saved. * @returns a function to call once when the request settles. On failure each * field still holding its optimistic value is reverted to the last value * confirmed by the server. */ protected applyOptimistic( params: Record ): (success: boolean) => void { const fields = getFieldsForModel(this); const keys = Object.keys(params).filter((key) => fields.includes(key)); const pending = pendingFields.get(this) ?? new Map(); pendingFields.set(this, pending); runInAction(() => { for (const key of keys) { const entry = pending.get(key); if (entry) { entry.count++; } else { pending.set(key, { confirmed: Reflect.get(this, key), count: 1 }); } Reflect.set(this, key, params[key]); } }); let settled = false; return action((success: boolean) => { if (settled) { return; } settled = true; for (const key of keys) { const entry = pending.get(key); if (!entry) { continue; } // A value changed since the optimistic write is newer, so it is kept. if (!success && isEqual(toJS(Reflect.get(this, key)), params[key])) { Reflect.set(this, key, entry.confirmed); if ( isEqual(Reflect.get(this.persistedAttributes, key), params[key]) ) { Reflect.set(this.persistedAttributes, key, toJS(entry.confirmed)); } } if (--entry.count === 0) { pending.delete(key); } } }); } updateData = action((data: Record) => { if (this.initialized) { LifecycleManager.executeHooks(this.constructor, "beforeChange", this); } // Change hooks compare incoming fields against confirmed values, not // optimistic ones. const pending = pendingFields.get(this); const previousAttributes = this.toAPI(); pending?.forEach((entry, key) => { if (key in data) { Reflect.set(previousAttributes, key, entry.confirmed); } }); let addedKeys = false; for (const key in data) { try { // Some models are serialized with the initialized flag, this should be ignored. if (key === "initialized") { continue; } const entry = pending?.get(key); if (entry) { entry.confirmed = data[key]; } if (isEqual(toJS(Reflect.get(this, key)), data[key])) { continue; } // A field declared without a default does not exist until it is first // assigned, so MobX could not annotate it when the model was created. addedKeys ||= !(key in this); Reflect.set(this, key, data[key]); } catch (error) { Logger.warn(`Error setting ${key} on model`, { error }); } } // Annotate any field that this payload introduced. Re-annotating a field // that is already observable is a no-op. if (addedKeys && this.initialized) { makeObservable(this); } this.isNew = false; this.persistedAttributes = this.toAPI(); if (this.initialized) { LifecycleManager.executeHooks( this.constructor, "afterChange", this, previousAttributes ); } }); fetch = (options?: JSONObject) => this.store.fetch(this.id, options); refresh = () => this.fetch({ force: true, }); delete = async () => { this.isSaving = true; try { LifecycleManager.executeHooks(this.constructor, "beforeDelete", this); const response = await this.store.delete(this); LifecycleManager.executeHooks(this.constructor, "afterDelete", this); return response; } finally { this.isSaving = false; } }; /** * Returns a plain object representation of fields on the model for * persistence to the server API * * @returns A plain object representation of the model */ toAPI = (): Partial => { const fields = getFieldsForModel(this); return pick(this, fields); }; /** * Returns a plain object representation of the model, containing its * identifier and declared fields only, safe to store outside of memory. * Internal state and observables are not included. * * @returns A plain object representation of the model */ toPersisted = (): PartialExcept => JSON.parse(JSON.stringify({ ...this.toAPI(), id: this.id })); /** * Returns a plain object representation of all the properties on the model * overrides the native toJSON method to avoid attempting to serialize store * * @returns A plain object representation of the model */ toJSON() { const output: Partial = {}; for (const property in this) { if ( // oxlint-disable-next-line no-prototype-builtins this.hasOwnProperty(property) && !["persistedAttributes", "store", "isSaving", "isNew"].includes( property ) ) { output[property] = this[property]; } } return output; } /** * Returns a boolean indicating if the model has changed since it was last * persisted to the server * * @returns boolean true if unsaved */ isDirty(): boolean { const attributes = this.toAPI(); if (Object.keys(attributes).length === 0) { Logger.warn("Checking dirty on model with no @Field decorators"); } return ( JSON.stringify(this.persistedAttributes) !== JSON.stringify(attributes) ); } protected persistedAttributes: Partial = {}; /** A boolean representing if the constructor has been called. */ private initialized = false; }