-
-
Notifications
You must be signed in to change notification settings - Fork 600
Expand file tree
/
Copy pathObjectStateMutations.ts
More file actions
259 lines (244 loc) · 7.41 KB
/
ObjectStateMutations.ts
File metadata and controls
259 lines (244 loc) · 7.41 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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import encode from './encode';
import CoreManager from './CoreManager';
import ParseFile from './ParseFile';
import ParseRelation from './ParseRelation';
import TaskQueue from './TaskQueue';
import { RelationOp } from './ParseOp';
import type { Op } from './ParseOp';
import type ParseObject from './ParseObject';
import { isDangerousKey } from "./isDangerousKey";
export type AttributeMap = Record<string, any>;
export type OpsMap = Record<string, Op>;
export type ObjectCache = Record<string, string>;
export interface State {
serverData: AttributeMap;
pendingOps: OpsMap[];
objectCache: ObjectCache;
tasks: TaskQueue;
existed: boolean;
}
export function defaultState(): State {
return {
serverData: Object.create(null),
pendingOps: [Object.create(null)],
objectCache: Object.create(null),
tasks: new TaskQueue(),
existed: false,
};
}
export function setServerData(serverData: AttributeMap, attributes: AttributeMap) {
for (const attr in attributes) {
// Skip properties from prototype chain
if (!Object.prototype.hasOwnProperty.call(attributes, attr)) {
continue;
}
// Skip dangerous keys that could pollute prototypes
if (isDangerousKey(attr)) {
continue;
}
if (typeof attributes[attr] !== "undefined") {
serverData[attr] = attributes[attr];
} else {
delete serverData[attr];
}
}
}
export function setPendingOp(pendingOps: OpsMap[], attr: string, op?: Op) {
// Skip dangerous keys that could pollute prototypes
if (isDangerousKey(attr)) {
return;
}
const last = pendingOps.length - 1;
if (op) {
pendingOps[last][attr] = op;
} else {
delete pendingOps[last][attr];
}
}
export function pushPendingState(pendingOps: OpsMap[]) {
pendingOps.push(Object.create(null));
}
export function popPendingState(pendingOps: OpsMap[]): OpsMap {
const first = pendingOps.shift();
if (!pendingOps.length) {
pendingOps[0] = Object.create(null);
}
return first;
}
export function mergeFirstPendingState(pendingOps: OpsMap[]) {
const first = popPendingState(pendingOps);
const next = pendingOps[0];
for (const attr in first) {
// Skip properties from prototype chain
if (!Object.prototype.hasOwnProperty.call(first, attr)) {
continue;
}
// Skip dangerous keys that could pollute prototypes
if (isDangerousKey(attr)) {
continue;
}
if (next[attr] && first[attr]) {
const merged = next[attr].mergeWith(first[attr]);
if (merged) {
next[attr] = merged;
}
} else {
next[attr] = first[attr];
}
}
}
export function estimateAttribute(
serverData: AttributeMap,
pendingOps: OpsMap[],
object: ParseObject,
attr: string
): any {
// Skip dangerous keys that could pollute prototypes
if (isDangerousKey(attr)) {
return undefined;
}
let value = serverData[attr];
for (let i = 0; i < pendingOps.length; i++) {
if (pendingOps[i][attr]) {
if (pendingOps[i][attr] instanceof RelationOp) {
if (object.id) {
value = (pendingOps[i][attr] as RelationOp).applyTo(value, object, attr);
}
} else {
value = pendingOps[i][attr].applyTo(value);
}
}
}
return value;
}
export function estimateAttributes(
serverData: AttributeMap,
pendingOps: OpsMap[],
object: ParseObject
): AttributeMap {
const data = Object.create(null);
let attr;
for (attr in serverData) {
data[attr] = serverData[attr];
}
for (let i = 0; i < pendingOps.length; i++) {
for (attr in pendingOps[i]) {
// Skip properties from prototype chain
if (!Object.prototype.hasOwnProperty.call(pendingOps[i], attr)) {
continue;
}
// Skip dangerous keys that could pollute prototypes
if (isDangerousKey(attr)) {
continue;
}
if (pendingOps[i][attr] instanceof RelationOp) {
if (object.id) {
data[attr] = (pendingOps[i][attr] as RelationOp).applyTo(data[attr], object, attr);
}
} else {
if (attr.includes('.')) {
// similar to nestedSet function
const fields = attr.split('.');
const last = fields[fields.length - 1];
let object = data;
for (let i = 0; i < fields.length - 1; i++) {
const key = fields[i];
if (!(key in object)) {
const nextKey = fields[i + 1];
if (!isNaN(nextKey)) {
object[key] = [];
} else {
object[key] = Object.create(null);
}
} else {
if (Array.isArray(object[key])) {
object[key] = [...object[key]];
} else {
object[key] = { ...object[key] };
}
}
object = object[key];
}
object[last] = pendingOps[i][attr].applyTo(object[last]);
} else {
data[attr] = pendingOps[i][attr].applyTo(data[attr]);
}
}
}
}
return data;
}
/**
* Allows setting properties/variables deep in an object.
* Converts a.b into { a: { b: value } } for dot notation on Objects
* Converts a.0.b into { a: [{ b: value }] } for dot notation on Arrays
*
* @param obj The object to assign the value to
* @param key The key to assign. If it's in a deeper path, then use dot notation (`prop1.prop2.prop3`)
* Note that intermediate object(s) in the nested path are automatically created if they don't exist.
* @param value The value to assign. If it's an `undefined` then the key is deleted.
*/
function nestedSet(obj, key, value) {
const paths = key.split('.');
for (let i = 0; i < paths.length - 1; i++) {
const path = paths[i];
if (!(path in obj)) {
const nextPath = paths[i + 1];
if (!isNaN(nextPath)) {
obj[path] = [];
} else {
obj[path] = Object.create(null);
}
}
obj = obj[path];
}
if (typeof value === 'undefined') {
delete obj[paths[paths.length - 1]];
} else {
obj[paths[paths.length - 1]] = value;
}
}
export function commitServerChanges(
serverData: AttributeMap,
objectCache: ObjectCache,
changes: AttributeMap
) {
const ParseObject = CoreManager.getParseObject();
for (const attr in changes) {
// Skip properties from prototype chain
if (!Object.prototype.hasOwnProperty.call(changes, attr)) {
continue;
}
// Skip dangerous keys that could pollute prototypes
if (isDangerousKey(attr)) {
continue;
}
const val = changes[attr];
// Set the change value to server data using nested path
nestedSet(serverData, attr, val);
// Initialize cache value and cache key
let cacheVal = val,
cacheKey = attr
// Handle nested attributes (dot notation)
if (attr.indexOf('.') >= 0) {
// Split attribute path and use first key for caching
const [firstKey, ..._rest] = attr.split('.')
cacheKey = firstKey
// Get the actual value from server data using first key
cacheVal = serverData[firstKey]
}
// Check if cache value should be serialized and stored
// Only serialize plain objects, not Parse instances
if (
cacheVal && // Value exists
typeof cacheVal === 'object' && // Is an object
!(cacheVal instanceof ParseObject) &&
!(cacheVal instanceof ParseFile) &&
!(cacheVal instanceof ParseRelation)
) {
const json = encode(cacheVal, false, true)
// Store serialized JSON string in object cache
objectCache[cacheKey] = JSON.stringify(json)
}
}
}