-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.js
118 lines (92 loc) · 2.76 KB
/
model.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import $ from 'jquery';
import * as defaultAdapter from '../adapters/default';
const xhrs = {};
export function fetch(brainstemKey, modelId, options = {}) {
const {
fetchOptions = {},
postFetchAction,
preFetchAction,
trackKey,
adapter = defaultAdapter,
} = options;
if (xhrs[trackKey] && xhrs[trackKey].state() === 'pending') xhrs[trackKey].abort();
return (dispatch, getState) => {
if (preFetchAction) dispatch(preFetchAction);
const xhr = adapter.fetchModel(brainstemKey, modelId, {
dispatch,
getState,
fetchOptions,
});
if (postFetchAction) xhr.done((model) => dispatch(postFetchAction(adapter.modelToId(model))));
if (trackKey) xhrs[trackKey] = xhr;
return xhr;
};
}
export function save(brainstemKey, modelId, attributes, options = {}) {
const {
saveOptions = {},
preSaveAction,
postSaveAction,
trackKey,
adapter = defaultAdapter,
} = options;
if (xhrs[trackKey] && xhrs[trackKey].state() === 'pending') xhrs[trackKey].abort();
return (dispatch, getState) => {
if (preSaveAction) dispatch(preSaveAction);
let xhr = adapter.saveModel(brainstemKey, modelId, attributes, {
dispatch,
getState,
saveOptions,
});
// backbone returns false when the model is invalid
if (!xhr.then) {
const validationErrors = adapter.validateModel(brainstemKey, attributes, {}) || {};
xhr = $.Deferred() // eslint-disable-line new-cap
.reject(new Error(Object.values(validationErrors).join(' ')))
.promise();
}
if (postSaveAction) {
xhr.done((response) => {
const newModelId = response.results[0].id;
dispatch(postSaveAction(newModelId));
});
}
if (trackKey) xhrs[trackKey] = xhr;
return xhr;
};
}
export function destroy(brainstemKey, modelId, options = {}) {
const {
deleteOptions = {},
trackKey,
adapter = defaultAdapter,
} = options;
if (xhrs[trackKey] && xhrs[trackKey].state() === 'pending') xhrs[trackKey].abort();
return (dispatch, getState) => {
const xhr = adapter.destroyModel(brainstemKey, modelId, {
dispatch,
getState,
deleteOptions,
});
if (trackKey) xhrs[trackKey] = xhr;
return xhr;
};
}
export function validate(brainstemKey, attributes, options = {}) {
const {
validateOptions = {},
preValidateAction,
postValidateAction,
adapter = defaultAdapter,
} = options;
return (dispatch, getState) => {
if (preValidateAction) dispatch(preValidateAction);
const validationErrors = adapter.validateModel(brainstemKey, attributes, {
dispatch,
getState,
validateOptions,
});
if (postValidateAction) { dispatch(postValidateAction(validationErrors)); }
return validationErrors;
};
}