-
Notifications
You must be signed in to change notification settings - Fork 134
/
sync-record-cache.ts
349 lines (307 loc) · 9.83 KB
/
sync-record-cache.ts
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import Orbit, { evented, Evented, Listener } from '@orbit/core';
import { deepGet, Dict } from '@orbit/utils';
import {
KeyMap,
Record,
RecordOperation,
Schema,
QueryBuilder,
QueryOrExpressions,
QueryExpression,
buildQuery,
TransformBuilder,
TransformBuilderFunc,
RecordIdentity
} from '@orbit/data';
import {
SyncOperationProcessor,
SyncOperationProcessorClass
} from './sync-operation-processor';
import SyncCacheIntegrityProcessor from './operation-processors/sync-cache-integrity-processor';
import SyncSchemaConsistencyProcessor from './operation-processors/sync-schema-consistency-processor';
import SyncSchemaValidationProcessor from './operation-processors/sync-schema-validation-processor';
import {
SyncPatchOperators,
SyncPatchOperator
} from './operators/sync-patch-operators';
import {
SyncQueryOperators,
SyncQueryOperator
} from './operators/sync-query-operators';
import {
SyncInversePatchOperators,
SyncInversePatchOperator
} from './operators/sync-inverse-patch-operators';
import {
SyncRecordAccessor,
RecordRelationshipIdentity
} from './record-accessor';
import { PatchResult } from './patch-result';
import { QueryResult, QueryResultData } from './query-result';
import { SyncLiveQuery } from './live-query/sync-live-query';
const { assert } = Orbit;
export interface SyncRecordCacheSettings {
schema: Schema;
keyMap?: KeyMap;
processors?: SyncOperationProcessorClass[];
transformBuilder?: TransformBuilder;
queryBuilder?: QueryBuilder;
queryOperators?: Dict<SyncQueryOperator>;
patchOperators?: Dict<SyncPatchOperator>;
inversePatchOperators?: Dict<SyncInversePatchOperator>;
}
@evented
export abstract class SyncRecordCache implements Evented, SyncRecordAccessor {
protected _keyMap?: KeyMap;
protected _schema: Schema;
protected _transformBuilder: TransformBuilder;
protected _queryBuilder: QueryBuilder;
protected _processors: SyncOperationProcessor[];
protected _queryOperators: Dict<SyncQueryOperator>;
protected _patchOperators: Dict<SyncPatchOperator>;
protected _inversePatchOperators: Dict<SyncInversePatchOperator>;
// Evented interface stubs
on: (event: string, listener: Listener) => () => void;
off: (event: string, listener?: Listener) => void;
one: (event: string, listener: Listener) => () => void;
emit: (event: string, ...args: any[]) => void;
listeners: (event: string) => Listener[];
constructor(settings: SyncRecordCacheSettings) {
assert(
"SyncRecordCache's `schema` must be specified in `settings.schema` constructor argument",
!!settings.schema
);
this._schema = settings.schema;
this._keyMap = settings.keyMap;
this._queryBuilder = settings.queryBuilder || new QueryBuilder();
this._transformBuilder =
settings.transformBuilder ||
new TransformBuilder({
recordInitializer: this._schema
});
this._queryOperators = settings.queryOperators || SyncQueryOperators;
this._patchOperators = settings.patchOperators || SyncPatchOperators;
this._inversePatchOperators =
settings.inversePatchOperators || SyncInversePatchOperators;
const processors: SyncOperationProcessorClass[] = settings.processors
? settings.processors
: [
SyncSchemaValidationProcessor,
SyncSchemaConsistencyProcessor,
SyncCacheIntegrityProcessor
];
this._processors = processors.map(Processor => {
let processor = new Processor(this);
assert(
'Each processor must extend SyncOperationProcessor',
processor instanceof SyncOperationProcessor
);
return processor;
});
}
get schema(): Schema {
return this._schema;
}
get keyMap(): KeyMap | undefined {
return this._keyMap;
}
get queryBuilder(): QueryBuilder {
return this._queryBuilder;
}
get transformBuilder(): TransformBuilder {
return this._transformBuilder;
}
get processors(): SyncOperationProcessor[] {
return this._processors;
}
getQueryOperator(op: string): SyncQueryOperator {
return this._queryOperators[op];
}
getPatchOperator(op: string): SyncPatchOperator {
return this._patchOperators[op];
}
getInversePatchOperator(op: string): SyncInversePatchOperator {
return this._inversePatchOperators[op];
}
// Abstract methods for getting records and relationships
abstract getRecordSync(recordIdentity: RecordIdentity): Record | undefined;
abstract getRecordsSync(
typeOrIdentities?: string | RecordIdentity[]
): Record[];
abstract getInverseRelationshipsSync(
record: RecordIdentity
): RecordRelationshipIdentity[];
// Abstract methods for setting records and relationships
abstract setRecordSync(record: Record): void;
abstract setRecordsSync(records: Record[]): void;
abstract removeRecordSync(recordIdentity: RecordIdentity): Record;
abstract removeRecordsSync(recordIdentities: RecordIdentity[]): Record[];
abstract addInverseRelationshipsSync(
relationships: RecordRelationshipIdentity[]
): void;
abstract removeInverseRelationshipsSync(
relationships: RecordRelationshipIdentity[]
): void;
getRelatedRecordSync(
identity: RecordIdentity,
relationship: string
): RecordIdentity | null | undefined {
const record = this.getRecordSync(identity);
if (record) {
return deepGet(record, ['relationships', relationship, 'data']);
}
return undefined;
}
getRelatedRecordsSync(
identity: RecordIdentity,
relationship: string
): RecordIdentity[] | undefined {
const record = this.getRecordSync(identity);
if (record) {
return deepGet(record, ['relationships', relationship, 'data']);
}
return undefined;
}
/**
* Queries the cache.
*/
query(
queryOrExpressions: QueryOrExpressions,
options?: object,
id?: string
): QueryResult {
const query = buildQuery(
queryOrExpressions,
options,
id,
this._queryBuilder
);
const results = this._query(query.expressions);
if (query.expressions.length === 1) {
return results[0];
}
return results;
}
/**
* Patches the cache with an operation or operations.
*/
patch(
operationOrOperations:
| RecordOperation
| RecordOperation[]
| TransformBuilderFunc
): PatchResult {
if (typeof operationOrOperations === 'function') {
operationOrOperations = operationOrOperations(this._transformBuilder) as
| RecordOperation
| RecordOperation[];
}
const result: PatchResult = {
inverse: [],
data: []
};
if (Array.isArray(operationOrOperations)) {
this._applyPatchOperations(
operationOrOperations as RecordOperation[],
result,
true
);
} else {
this._applyPatchOperation(
operationOrOperations as RecordOperation,
result,
true
);
}
result.inverse.reverse();
return result;
}
liveQuery(
queryOrExpressions: QueryOrExpressions,
options?: object,
id?: string
): SyncLiveQuery {
const query = buildQuery(
queryOrExpressions,
options,
id,
this.queryBuilder
);
return new SyncLiveQuery({
cache: this,
query
});
}
/////////////////////////////////////////////////////////////////////////////
// Protected methods
/////////////////////////////////////////////////////////////////////////////
protected _query(expressions: QueryExpression[]): QueryResultData[] {
const results: QueryResultData[] = [];
for (let expression of expressions) {
const queryOperator = this.getQueryOperator(expression.op);
if (!queryOperator) {
throw new Error(`Unable to find query operator: ${expression.op}`);
}
results.push(queryOperator(this, expression));
}
return results;
}
protected _applyPatchOperations(
ops: RecordOperation[],
result: PatchResult,
primary = false
) {
ops.forEach(op => this._applyPatchOperation(op, result, primary));
}
protected _applyPatchOperation(
operation: RecordOperation,
result: PatchResult,
primary = false
) {
if ((operation.op as string) === 'replaceRecord') {
Orbit.deprecate(
'The `replaceRecord` operation has been deprecated - use `updateRecord` instead.'
);
operation = {
op: 'updateRecord',
record: operation.record
};
}
this._processors.forEach(processor => processor.validate(operation));
const inversePatchOperator = this.getInversePatchOperator(operation.op);
const inverseOp: RecordOperation | undefined = inversePatchOperator(
this,
operation
);
if (inverseOp) {
result.inverse.push(inverseOp);
// Query and perform related `before` operations
this._processors
.map(processor => processor.before(operation))
.forEach(ops => this._applyPatchOperations(ops, result));
// Query related `after` operations before performing
// the requested operation. These will be applied on success.
let preparedOps = this._processors.map(processor =>
processor.after(operation)
);
// Perform the requested operation
let patchOperator = this.getPatchOperator(operation.op);
let data = patchOperator(this, operation);
if (primary) {
result.data.push(data);
}
// Query and perform related `immediate` operations
this._processors.forEach(processor => processor.immediate(operation));
// Emit event
this.emit('patch', operation, data);
// Perform prepared operations after performing the requested operation
preparedOps.forEach(ops => this._applyPatchOperations(ops, result));
// Query and perform related `finally` operations
this._processors
.map(processor => processor.finally(operation))
.forEach(ops => this._applyPatchOperations(ops, result));
} else if (primary) {
result.data.push(null);
}
}
}