mirror of
https://github.com/outline/outline.git
synced 2026-11-20 21:23:06 +03:00
* feat: Make model.save() optimistic with rollback on failure Apply saved params to the model immediately so MobX observers update without waiting for the server, and roll the model back to its previous state when the request fails. New models with a client-generated id are optimistically added to the store and removed again on failure. * chore: Apply formatter and test naming convention * fix: Scope optimistic saves to passed fields and confirmed values Only fields passed to save() are applied optimistically, and a failure reverts a field only while it still holds the optimistic value. Change hooks compare against the last confirmed values so they run when the server responds. The optimistic store add is removed. * refactor: Use optimistic save for preferences and field toggles Add savePreference to User, Team and Document, and pass changed fields to save() so they revert on failure. * fix: Only compare incoming fields against confirmed values in change hooks --------- Co-authored-by: Claude <noreply@anthropic.com>
440 lines
13 KiB
TypeScript
440 lines
13 KiB
TypeScript
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<string | symbol, unknown> = 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<Model, Map<string, PendingField>>();
|
|
|
|
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<T extends Model>(
|
|
record: Record<string, unknown>
|
|
): PartialExcept<T, "id"> {
|
|
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<Model>;
|
|
|
|
constructor(_fields: Record<string, unknown>, store: Store<Model>) {
|
|
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<string, unknown>) {
|
|
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<unknown> {
|
|
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<string, unknown>,
|
|
options?: Record<string, string | boolean | number | undefined>
|
|
): Promise<Model> => {
|
|
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<string, unknown>
|
|
): (success: boolean) => void {
|
|
const fields = getFieldsForModel(this);
|
|
const keys = Object.keys(params).filter((key) => fields.includes(key));
|
|
const pending = pendingFields.get(this) ?? new Map<string, PendingField>();
|
|
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<string, unknown>) => {
|
|
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<Model> => {
|
|
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<Model, "id"> =>
|
|
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<typeof this> = {};
|
|
|
|
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<Model> = {};
|
|
|
|
/** A boolean representing if the constructor has been called. */
|
|
private initialized = false;
|
|
}
|