Files
outline/app/models/BaseModel.ts
T
2021-07-04 16:06:23 -04:00

52 lines
1.0 KiB
TypeScript

import { set, observable } from "mobx";
export default class BaseModel {
@observable
id: string;
@observable
isSaving: boolean;
store: any;
constructor(fields: any, store: any) {
set(this, fields);
this.store = store;
}
save = async (params?: any | null) => {
this.isSaving = true;
try {
// ensure that the id is passed if the document has one
if (params) params = { ...params, id: this.id };
const model = await this.store.save(params || this.toJS());
// if saving is successful set the new values on the model itself
set(this, { ...params, ...model });
return model;
} finally {
this.isSaving = false;
}
};
fetch = (options?: any) => {
return this.store.fetch(this.id, options);
};
refresh = () => {
return this.fetch({ force: true });
};
delete = async () => {
this.isSaving = true;
try {
return await this.store.delete(this);
} finally {
this.isSaving = false;
}
};
toJS = (): any => {
return { ...this };
};
}