-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathpersist.ts
More file actions
75 lines (65 loc) · 2.31 KB
/
persist.ts
File metadata and controls
75 lines (65 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import Context from "../common/context";
import { ActionParams, Data } from "../support/interfaces";
import Action from "./action";
import Model from "../orm/model";
import { Store } from "../orm/store";
/**
* Persist action for sending a create mutation. Will be used for record.$persist().
*/
export default class Persist extends Action {
/**
* @param {any} state The Vuex state
* @param {DispatchFunction} dispatch Vuex Dispatch method for the model
* @param {string} id ID of the record to persist
* @returns {Promise<Data>} The saved record
*/
public static async call(
{ state, dispatch }: ActionParams,
{ id, args }: ActionParams
): Promise<Data> {
if (id) {
const model = this.getModelFromState(state!);
const mutationName = Context.getInstance().adapter.getNameForPersist(model);
const oldRecord = model.baseModel
.query()
.withAllRecursive()
.where("$id", id)
.first()!;
const mockReturnValue = model.$mockHook("persist", {
id,
args: args || {}
});
if (mockReturnValue) {
const newRecord = await Store.insertData(mockReturnValue, dispatch!);
await this.deleteObsoleteRecord(model, newRecord, oldRecord);
return newRecord;
}
// Arguments
args = this.prepareArgs(args);
this.addRecordToArgs(args, model, oldRecord);
// Send mutation
const newRecord = await Action.mutation(mutationName, args as Data, dispatch!, model);
// Delete the old record if necessary
await this.deleteObsoleteRecord(model, newRecord, oldRecord);
return newRecord;
} else {
/* istanbul ignore next */
throw new Error("The persist action requires the 'id' to be set");
}
}
/**
* It's very likely that the server generated different ID for this record.
* In this case Action.mutation has inserted a new record instead of updating the existing one.
*
* @param {Model} model
* @param {Data} record
* @returns {Promise<void>}
*/
private static async deleteObsoleteRecord(model: Model, newRecord: Data, oldRecord: Data) {
if (newRecord && oldRecord && newRecord.id !== oldRecord.id) {
Context.getInstance().logger.log("Dropping deprecated record", oldRecord);
return oldRecord.$delete();
}
return null;
}
}