@ember-data/legacy-compat 4.12.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +11 -0
- package/README.md +26 -0
- package/addon/-private.js +1 -0
- package/addon/-private.js.map +1 -0
- package/addon/fetch-manager-2716abb1.js +703 -0
- package/addon/fetch-manager-2716abb1.js.map +1 -0
- package/addon/index.js +315 -0
- package/addon/index.js.map +1 -0
- package/addon-main.js +117 -0
- package/package.json +69 -0
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
import { macroCondition, getOwnConfig, isDevelopingApp, importSync } from '@embroider/macros';
|
|
2
|
+
import { deprecate, assert, warn } from '@ember/debug';
|
|
3
|
+
import { SOURCE, coerceId } from '@ember-data/store/-private';
|
|
4
|
+
import { _backburner } from '@ember/runloop';
|
|
5
|
+
import RSVP, { resolve } from 'rsvp';
|
|
6
|
+
/**
|
|
7
|
+
SnapshotRecordArray is not directly instantiable.
|
|
8
|
+
Instances are provided to consuming application's
|
|
9
|
+
adapters for certain requests.
|
|
10
|
+
|
|
11
|
+
@class SnapshotRecordArray
|
|
12
|
+
@public
|
|
13
|
+
*/
|
|
14
|
+
class SnapshotRecordArray {
|
|
15
|
+
/**
|
|
16
|
+
SnapshotRecordArray is not directly instantiable.
|
|
17
|
+
Instances are provided to consuming application's
|
|
18
|
+
adapters and serializers for certain requests.
|
|
19
|
+
@method constructor
|
|
20
|
+
@private
|
|
21
|
+
@constructor
|
|
22
|
+
@param {Store} store
|
|
23
|
+
@param {string} type
|
|
24
|
+
@param options
|
|
25
|
+
*/
|
|
26
|
+
constructor(store, type, options = {}) {
|
|
27
|
+
this.__store = store;
|
|
28
|
+
/**
|
|
29
|
+
An array of snapshots
|
|
30
|
+
@private
|
|
31
|
+
@property _snapshots
|
|
32
|
+
@type {Array}
|
|
33
|
+
*/
|
|
34
|
+
this._snapshots = null;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
The modelName of the underlying records for the snapshots in the array, as a Model
|
|
38
|
+
@property modelName
|
|
39
|
+
@public
|
|
40
|
+
@type {Model}
|
|
41
|
+
*/
|
|
42
|
+
this.modelName = type;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
A hash of adapter options passed into the store method for this request.
|
|
46
|
+
Example
|
|
47
|
+
```app/adapters/post.js
|
|
48
|
+
import MyCustomAdapter from './custom-adapter';
|
|
49
|
+
export default class PostAdapter extends MyCustomAdapter {
|
|
50
|
+
findAll(store, type, sinceToken, snapshotRecordArray) {
|
|
51
|
+
if (snapshotRecordArray.adapterOptions.subscribe) {
|
|
52
|
+
// ...
|
|
53
|
+
}
|
|
54
|
+
// ...
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
@property adapterOptions
|
|
59
|
+
@public
|
|
60
|
+
@type {Object}
|
|
61
|
+
*/
|
|
62
|
+
this.adapterOptions = options.adapterOptions;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
The relationships to include for this request.
|
|
66
|
+
Example
|
|
67
|
+
```app/adapters/application.js
|
|
68
|
+
import Adapter from '@ember-data/adapter';
|
|
69
|
+
export default class ApplicationAdapter extends Adapter {
|
|
70
|
+
findAll(store, type, snapshotRecordArray) {
|
|
71
|
+
let url = `/${type.modelName}?include=${encodeURIComponent(snapshotRecordArray.include)}`;
|
|
72
|
+
return fetch(url).then((response) => response.json())
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
@property include
|
|
77
|
+
@public
|
|
78
|
+
@type {String|Array}
|
|
79
|
+
*/
|
|
80
|
+
this.include = options.include;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
An array of records
|
|
85
|
+
@property _recordArray
|
|
86
|
+
@private
|
|
87
|
+
@type {Array}
|
|
88
|
+
*/
|
|
89
|
+
get _recordArray() {
|
|
90
|
+
return this.__store.peekAll(this.modelName);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
Number of records in the array
|
|
95
|
+
Example
|
|
96
|
+
```app/adapters/post.js
|
|
97
|
+
import JSONAPIAdapter from '@ember-data/adapter/json-api';
|
|
98
|
+
export default class PostAdapter extends JSONAPIAdapter {
|
|
99
|
+
shouldReloadAll(store, snapshotRecordArray) {
|
|
100
|
+
return !snapshotRecordArray.length;
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
```
|
|
104
|
+
@property length
|
|
105
|
+
@public
|
|
106
|
+
@type {Number}
|
|
107
|
+
*/
|
|
108
|
+
get length() {
|
|
109
|
+
return this._recordArray.length;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
Get snapshots of the underlying record array
|
|
114
|
+
Example
|
|
115
|
+
```app/adapters/post.js
|
|
116
|
+
import JSONAPIAdapter from '@ember-data/adapter/json-api';
|
|
117
|
+
export default class PostAdapter extends JSONAPIAdapter {
|
|
118
|
+
shouldReloadAll(store, snapshotArray) {
|
|
119
|
+
let snapshots = snapshotArray.snapshots();
|
|
120
|
+
return snapshots.any(function(ticketSnapshot) {
|
|
121
|
+
let timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt'), 'minutes');
|
|
122
|
+
if (timeDiff > 20) {
|
|
123
|
+
return true;
|
|
124
|
+
} else {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
@method snapshots
|
|
132
|
+
@public
|
|
133
|
+
@return {Array} Array of snapshots
|
|
134
|
+
*/
|
|
135
|
+
snapshots() {
|
|
136
|
+
if (this._snapshots !== null) {
|
|
137
|
+
return this._snapshots;
|
|
138
|
+
}
|
|
139
|
+
const {
|
|
140
|
+
_instanceCache
|
|
141
|
+
} = this.__store;
|
|
142
|
+
this._snapshots = this._recordArray[SOURCE].map(identifier => _instanceCache.createSnapshot(identifier));
|
|
143
|
+
return this._snapshots;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (macroCondition(getOwnConfig().deprecations.DEPRECATE_SNAPSHOT_MODEL_CLASS_ACCESS)) {
|
|
147
|
+
/**
|
|
148
|
+
The type of the underlying records for the snapshots in the array, as a Model
|
|
149
|
+
@deprecated
|
|
150
|
+
@property type
|
|
151
|
+
@public
|
|
152
|
+
@type {Model}
|
|
153
|
+
*/
|
|
154
|
+
Object.defineProperty(SnapshotRecordArray.prototype, 'type', {
|
|
155
|
+
get() {
|
|
156
|
+
deprecate(`Using SnapshotRecordArray.type to access the ModelClass for a record is deprecated. Use store.modelFor(<modelName>) instead.`, false, {
|
|
157
|
+
id: 'ember-data:deprecate-snapshot-model-class-access',
|
|
158
|
+
until: '5.0',
|
|
159
|
+
for: 'ember-data',
|
|
160
|
+
since: {
|
|
161
|
+
available: '4.5.0',
|
|
162
|
+
enabled: '4.5.0'
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
// @ts-expect-error
|
|
166
|
+
return this._recordArray.type;
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
function _bind(fn, ...args) {
|
|
171
|
+
return function () {
|
|
172
|
+
return fn.apply(undefined, args);
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function _guard(promise, test) {
|
|
176
|
+
let guarded = promise.finally(() => {
|
|
177
|
+
if (!test()) {
|
|
178
|
+
guarded._subscribers.length = 0;
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
return guarded;
|
|
182
|
+
}
|
|
183
|
+
function _objectIsAlive(object) {
|
|
184
|
+
return !(object.isDestroyed || object.isDestroying);
|
|
185
|
+
}
|
|
186
|
+
function guardDestroyedStore(promise, store, label) {
|
|
187
|
+
let token;
|
|
188
|
+
if (isDevelopingApp()) {
|
|
189
|
+
token = store._trackAsyncRequestStart(label);
|
|
190
|
+
}
|
|
191
|
+
let wrapperPromise = resolve(promise, label).then(_v => {
|
|
192
|
+
if (!_objectIsAlive(store)) {
|
|
193
|
+
if (macroCondition(getOwnConfig().deprecations.DEPRECATE_RSVP_PROMISE)) {
|
|
194
|
+
deprecate(`A Promise did not resolve by the time the store was destroyed. This will error in a future release.`, false, {
|
|
195
|
+
id: 'ember-data:rsvp-unresolved-async',
|
|
196
|
+
until: '5.0',
|
|
197
|
+
for: '@ember-data/store',
|
|
198
|
+
since: {
|
|
199
|
+
available: '4.5',
|
|
200
|
+
enabled: '4.5'
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return promise;
|
|
206
|
+
});
|
|
207
|
+
return _guard(wrapperPromise, () => {
|
|
208
|
+
if (isDevelopingApp()) {
|
|
209
|
+
store._trackAsyncRequestEnd(token);
|
|
210
|
+
}
|
|
211
|
+
return _objectIsAlive(store);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
function assertIdentifierHasId(identifier) {
|
|
215
|
+
assert(`Attempted to schedule a fetch for a record without an id.`, identifier.id !== null);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
This is a helper method that validates a JSON API top-level document
|
|
220
|
+
|
|
221
|
+
The format of a document is described here:
|
|
222
|
+
http://jsonapi.org/format/#document-top-level
|
|
223
|
+
|
|
224
|
+
@internal
|
|
225
|
+
*/
|
|
226
|
+
function validateDocumentStructure(doc) {
|
|
227
|
+
if (isDevelopingApp()) {
|
|
228
|
+
let errors = [];
|
|
229
|
+
if (!doc || typeof doc !== 'object') {
|
|
230
|
+
errors.push('Top level of a JSON API document must be an object');
|
|
231
|
+
} else {
|
|
232
|
+
if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) {
|
|
233
|
+
errors.push('One or more of the following keys must be present: "data", "errors", "meta".');
|
|
234
|
+
} else {
|
|
235
|
+
if ('data' in doc && 'errors' in doc) {
|
|
236
|
+
errors.push('Top level keys "errors" and "data" cannot both be present in a JSON API document');
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if ('data' in doc) {
|
|
240
|
+
if (!(doc.data === null || Array.isArray(doc.data) || typeof doc.data === 'object')) {
|
|
241
|
+
errors.push('data must be null, an object, or an array');
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if ('meta' in doc) {
|
|
245
|
+
if (typeof doc.meta !== 'object') {
|
|
246
|
+
errors.push('meta must be an object');
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if ('errors' in doc) {
|
|
250
|
+
if (!Array.isArray(doc.errors)) {
|
|
251
|
+
errors.push('errors must be an array');
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if ('links' in doc) {
|
|
255
|
+
if (typeof doc.links !== 'object') {
|
|
256
|
+
errors.push('links must be an object');
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
if ('jsonapi' in doc) {
|
|
260
|
+
if (typeof doc.jsonapi !== 'object') {
|
|
261
|
+
errors.push('jsonapi must be an object');
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if ('included' in doc) {
|
|
265
|
+
if (typeof doc.included !== 'object') {
|
|
266
|
+
errors.push('included must be an array');
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
assert(`Response must be normalized to a valid JSON API document:\n\t* ${errors.join('\n\t* ')}`, errors.length === 0);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
function normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) {
|
|
274
|
+
let normalizedResponse = serializer ? serializer.normalizeResponse(store, modelClass, payload, id, requestType) : payload;
|
|
275
|
+
validateDocumentStructure(normalizedResponse);
|
|
276
|
+
return normalizedResponse;
|
|
277
|
+
}
|
|
278
|
+
function payloadIsNotBlank(adapterPayload) {
|
|
279
|
+
if (Array.isArray(adapterPayload)) {
|
|
280
|
+
return true;
|
|
281
|
+
} else {
|
|
282
|
+
return Object.keys(adapterPayload || {}).length !== 0;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
const SaveOp = Symbol('SaveOp');
|
|
286
|
+
class FetchManager {
|
|
287
|
+
// saves which are pending in the runloop
|
|
288
|
+
|
|
289
|
+
// fetches pending in the runloop, waiting to be coalesced
|
|
290
|
+
|
|
291
|
+
constructor(store) {
|
|
292
|
+
this._store = store;
|
|
293
|
+
// used to keep track of all the find requests that need to be coalesced
|
|
294
|
+
this._pendingFetch = new Map();
|
|
295
|
+
this._pendingSave = [];
|
|
296
|
+
this.requestCache = store.getRequestStateService();
|
|
297
|
+
this.isDestroyed = false;
|
|
298
|
+
}
|
|
299
|
+
_createSnapshot(identifier, options) {
|
|
300
|
+
return this._store._instanceCache.createSnapshot(identifier, options);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
This method is called by `record.save`, and gets passed a
|
|
305
|
+
resolver for the promise that `record.save` returns.
|
|
306
|
+
It schedules saving to happen at the end of the run loop.
|
|
307
|
+
@internal
|
|
308
|
+
*/
|
|
309
|
+
scheduleSave(identifier, options) {
|
|
310
|
+
let resolver = RSVP.defer(isDevelopingApp() ? `DS: Model#save ${identifier.lid}` : '');
|
|
311
|
+
let query = {
|
|
312
|
+
op: 'saveRecord',
|
|
313
|
+
recordIdentifier: identifier,
|
|
314
|
+
options
|
|
315
|
+
};
|
|
316
|
+
let queryRequest = {
|
|
317
|
+
data: [query]
|
|
318
|
+
};
|
|
319
|
+
const snapshot = this._createSnapshot(identifier, options);
|
|
320
|
+
const pendingSaveItem = {
|
|
321
|
+
snapshot: snapshot,
|
|
322
|
+
resolver: resolver,
|
|
323
|
+
identifier,
|
|
324
|
+
options,
|
|
325
|
+
queryRequest
|
|
326
|
+
};
|
|
327
|
+
this._pendingSave.push(pendingSaveItem);
|
|
328
|
+
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
329
|
+
_backburner.scheduleOnce('actions', this, this._flushPendingSaves);
|
|
330
|
+
this.requestCache.enqueue(resolver.promise, pendingSaveItem.queryRequest);
|
|
331
|
+
return resolver.promise;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
This method is called at the end of the run loop, and
|
|
336
|
+
flushes any records passed into `scheduleSave`
|
|
337
|
+
@internal
|
|
338
|
+
*/
|
|
339
|
+
_flushPendingSaves() {
|
|
340
|
+
const store = this._store;
|
|
341
|
+
let pending = this._pendingSave.slice();
|
|
342
|
+
this._pendingSave = [];
|
|
343
|
+
for (let i = 0, j = pending.length; i < j; i++) {
|
|
344
|
+
let pendingItem = pending[i];
|
|
345
|
+
_flushPendingSave(store, pendingItem);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
scheduleFetch(identifier, options) {
|
|
349
|
+
// TODO Probably the store should pass in the query object
|
|
350
|
+
let shouldTrace = isDevelopingApp() && this._store.generateStackTracesForTrackedRequests;
|
|
351
|
+
let query = {
|
|
352
|
+
op: 'findRecord',
|
|
353
|
+
recordIdentifier: identifier,
|
|
354
|
+
options
|
|
355
|
+
};
|
|
356
|
+
let queryRequest = {
|
|
357
|
+
data: [query]
|
|
358
|
+
};
|
|
359
|
+
let pendingFetch = this.getPendingFetch(identifier, options);
|
|
360
|
+
if (pendingFetch) {
|
|
361
|
+
return pendingFetch;
|
|
362
|
+
}
|
|
363
|
+
let id = identifier.id;
|
|
364
|
+
let modelName = identifier.type;
|
|
365
|
+
let resolver = RSVP.defer(`Fetching ${modelName}' with id: ${id}`);
|
|
366
|
+
let pendingFetchItem = {
|
|
367
|
+
identifier,
|
|
368
|
+
resolver,
|
|
369
|
+
options,
|
|
370
|
+
queryRequest
|
|
371
|
+
};
|
|
372
|
+
if (isDevelopingApp()) {
|
|
373
|
+
if (shouldTrace) {
|
|
374
|
+
let trace;
|
|
375
|
+
try {
|
|
376
|
+
throw new Error(`Trace Origin for scheduled fetch for ${modelName}:${id}.`);
|
|
377
|
+
} catch (e) {
|
|
378
|
+
trace = e;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// enable folks to discover the origin of this findRecord call when
|
|
382
|
+
// debugging. Ideally we would have a tracked queue for requests with
|
|
383
|
+
// labels or local IDs that could be used to merge this trace with
|
|
384
|
+
// the trace made available when we detect an async leak
|
|
385
|
+
pendingFetchItem.trace = trace;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
let resolverPromise = resolver.promise;
|
|
389
|
+
const store = this._store;
|
|
390
|
+
const isLoading = !store._instanceCache.recordIsLoaded(identifier); // we don't use isLoading directly because we are the request
|
|
391
|
+
|
|
392
|
+
const promise = resolverPromise.then(payload => {
|
|
393
|
+
// ensure that regardless of id returned we assign to the correct record
|
|
394
|
+
if (payload.data && !Array.isArray(payload.data)) {
|
|
395
|
+
payload.data.lid = identifier.lid;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// additional data received in the payload
|
|
399
|
+
// may result in the merging of identifiers (and thus records)
|
|
400
|
+
let potentiallyNewIm = store._push(payload);
|
|
401
|
+
if (potentiallyNewIm && !Array.isArray(potentiallyNewIm)) {
|
|
402
|
+
return potentiallyNewIm;
|
|
403
|
+
}
|
|
404
|
+
return identifier;
|
|
405
|
+
}, error => {
|
|
406
|
+
const cache = macroCondition(getOwnConfig().deprecations.DEPRECATE_V1_RECORD_DATA) ? store._instanceCache.peek({
|
|
407
|
+
identifier,
|
|
408
|
+
bucket: 'resourceCache'
|
|
409
|
+
}) : store.cache;
|
|
410
|
+
if (!cache || cache.isEmpty(identifier) || isLoading) {
|
|
411
|
+
let isReleasable = true;
|
|
412
|
+
if (macroCondition(getOwnConfig().packages.HAS_GRAPH_PACKAGE)) {
|
|
413
|
+
if (!cache) {
|
|
414
|
+
const graphFor = importSync('@ember-data/graph/-private').graphFor;
|
|
415
|
+
const graph = graphFor(store);
|
|
416
|
+
isReleasable = graph.isReleasable(identifier);
|
|
417
|
+
if (!isReleasable) {
|
|
418
|
+
graph.unload(identifier, true);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (cache || isReleasable) {
|
|
423
|
+
store._instanceCache.unloadRecord(identifier);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
throw error;
|
|
427
|
+
});
|
|
428
|
+
if (this._pendingFetch.size === 0) {
|
|
429
|
+
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
430
|
+
_backburner.schedule('actions', this, this.flushAllPendingFetches);
|
|
431
|
+
}
|
|
432
|
+
let fetches = this._pendingFetch;
|
|
433
|
+
if (!fetches.has(modelName)) {
|
|
434
|
+
fetches.set(modelName, []);
|
|
435
|
+
}
|
|
436
|
+
fetches.get(modelName).push(pendingFetchItem);
|
|
437
|
+
pendingFetchItem.promise = promise;
|
|
438
|
+
this.requestCache.enqueue(resolverPromise, pendingFetchItem.queryRequest);
|
|
439
|
+
return promise;
|
|
440
|
+
}
|
|
441
|
+
getPendingFetch(identifier, options) {
|
|
442
|
+
let pendingFetches = this._pendingFetch.get(identifier.type);
|
|
443
|
+
|
|
444
|
+
// We already have a pending fetch for this
|
|
445
|
+
if (pendingFetches) {
|
|
446
|
+
let matchingPendingFetch = pendingFetches.find(fetch => fetch.identifier === identifier && isSameRequest(options, fetch.options));
|
|
447
|
+
if (matchingPendingFetch) {
|
|
448
|
+
return matchingPendingFetch.promise;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
flushAllPendingFetches() {
|
|
453
|
+
if (this.isDestroyed) {
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
const store = this._store;
|
|
457
|
+
this._pendingFetch.forEach((fetchItem, type) => _flushPendingFetchForType(store, fetchItem, type));
|
|
458
|
+
this._pendingFetch.clear();
|
|
459
|
+
}
|
|
460
|
+
fetchDataIfNeededForIdentifier(identifier, options = {}) {
|
|
461
|
+
// pre-loading will change the isEmpty value
|
|
462
|
+
const isEmpty = _isEmpty(this._store._instanceCache, identifier);
|
|
463
|
+
const isLoading = _isLoading(this._store._instanceCache, identifier);
|
|
464
|
+
let promise;
|
|
465
|
+
if (isEmpty) {
|
|
466
|
+
assertIdentifierHasId(identifier);
|
|
467
|
+
promise = this.scheduleFetch(identifier, options);
|
|
468
|
+
} else if (isLoading) {
|
|
469
|
+
promise = this.getPendingFetch(identifier, options);
|
|
470
|
+
assert(`Expected to find a pending request for a record in the loading state, but found none`, promise);
|
|
471
|
+
} else {
|
|
472
|
+
promise = resolve(identifier);
|
|
473
|
+
}
|
|
474
|
+
return promise;
|
|
475
|
+
}
|
|
476
|
+
destroy() {
|
|
477
|
+
this.isDestroyed = true;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
function _isEmpty(instanceCache, identifier) {
|
|
481
|
+
const cache = macroCondition(getOwnConfig().deprecations.DEPRECATE_V1_RECORD_DATA) ? instanceCache.__instances.resourceCache.get(identifier) : instanceCache.cache;
|
|
482
|
+
if (!cache) {
|
|
483
|
+
return true;
|
|
484
|
+
}
|
|
485
|
+
const isNew = cache.isNew(identifier);
|
|
486
|
+
const isDeleted = cache.isDeleted(identifier);
|
|
487
|
+
const isEmpty = cache.isEmpty(identifier);
|
|
488
|
+
return (!isNew || isDeleted) && isEmpty;
|
|
489
|
+
}
|
|
490
|
+
function _isLoading(cache, identifier) {
|
|
491
|
+
const req = cache.store.getRequestStateService();
|
|
492
|
+
// const fulfilled = req.getLastRequestForRecord(identifier);
|
|
493
|
+
const isLoaded = cache.recordIsLoaded(identifier);
|
|
494
|
+
return !isLoaded &&
|
|
495
|
+
// fulfilled === null &&
|
|
496
|
+
req.getPendingRequestsForRecord(identifier).some(req => req.type === 'query');
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// this function helps resolve whether we have a pending request that we should use instead
|
|
500
|
+
function isSameRequest(options = {}, existingOptions = {}) {
|
|
501
|
+
let includedMatches = !options.include || options.include === existingOptions.include;
|
|
502
|
+
let adapterOptionsMatches = options.adapterOptions === existingOptions.adapterOptions;
|
|
503
|
+
return includedMatches && adapterOptionsMatches;
|
|
504
|
+
}
|
|
505
|
+
function _findMany(store, adapter, modelName, snapshots) {
|
|
506
|
+
let modelClass = store.modelFor(modelName); // `adapter.findMany` gets the modelClass still
|
|
507
|
+
const ids = snapshots.map(s => s.id);
|
|
508
|
+
assert(`Cannot fetch a record without an id`, ids.every(v => v !== null));
|
|
509
|
+
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
510
|
+
assert(`Expected this adapter to implement findMany for coalescing`, adapter.findMany);
|
|
511
|
+
let promise = adapter.findMany(store, modelClass, ids, snapshots);
|
|
512
|
+
let label = `DS: Handle Adapter#findMany of '${modelName}'`;
|
|
513
|
+
if (promise === undefined) {
|
|
514
|
+
throw new Error('adapter.findMany returned undefined, this was very likely a mistake');
|
|
515
|
+
}
|
|
516
|
+
promise = guardDestroyedStore(promise, store, label);
|
|
517
|
+
return promise.then(adapterPayload => {
|
|
518
|
+
assert(`You made a 'findMany' request for '${modelName}' records with ids '[${ids.join(',')}]', but the adapter's response did not have any data`, !!payloadIsNotBlank(adapterPayload));
|
|
519
|
+
let serializer = store.serializerFor(modelName);
|
|
520
|
+
let payload = normalizeResponseHelper(serializer, store, modelClass, adapterPayload, null, 'findMany');
|
|
521
|
+
return payload;
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
function rejectFetchedItems(fetchMap, snapshots, error) {
|
|
525
|
+
for (let i = 0, l = snapshots.length; i < l; i++) {
|
|
526
|
+
let snapshot = snapshots[i];
|
|
527
|
+
let pair = fetchMap.get(snapshot);
|
|
528
|
+
if (pair) {
|
|
529
|
+
pair.resolver.reject(error || new Error(`Expected: '<${snapshot.modelName}:${snapshot.id}>' to be present in the adapter provided payload, but it was not found.`));
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
function handleFoundRecords(store, fetchMap, snapshots, coalescedPayload) {
|
|
534
|
+
/*
|
|
535
|
+
It is possible that the same ID is included multiple times
|
|
536
|
+
via multiple snapshots. This happens when more than one
|
|
537
|
+
options hash was supplied, each of which must be uniquely
|
|
538
|
+
accounted for.
|
|
539
|
+
However, since we can't map from response to a specific
|
|
540
|
+
options object, we resolve all snapshots by id with
|
|
541
|
+
the first response we see.
|
|
542
|
+
*/
|
|
543
|
+
let snapshotsById = new Map();
|
|
544
|
+
for (let i = 0; i < snapshots.length; i++) {
|
|
545
|
+
let id = snapshots[i].id;
|
|
546
|
+
let snapshotGroup = snapshotsById.get(id);
|
|
547
|
+
if (!snapshotGroup) {
|
|
548
|
+
snapshotGroup = [];
|
|
549
|
+
snapshotsById.set(id, snapshotGroup);
|
|
550
|
+
}
|
|
551
|
+
snapshotGroup.push(snapshots[i]);
|
|
552
|
+
}
|
|
553
|
+
const included = Array.isArray(coalescedPayload.included) ? coalescedPayload.included : [];
|
|
554
|
+
|
|
555
|
+
// resolve found records
|
|
556
|
+
let resources = coalescedPayload.data;
|
|
557
|
+
for (let i = 0, l = resources.length; i < l; i++) {
|
|
558
|
+
let resource = resources[i];
|
|
559
|
+
let snapshotGroup = snapshotsById.get(resource.id);
|
|
560
|
+
snapshotsById.delete(resource.id);
|
|
561
|
+
if (!snapshotGroup) {
|
|
562
|
+
// TODO consider whether this should be a deprecation/assertion
|
|
563
|
+
included.push(resource);
|
|
564
|
+
} else {
|
|
565
|
+
snapshotGroup.forEach(snapshot => {
|
|
566
|
+
let pair = fetchMap.get(snapshot);
|
|
567
|
+
let resolver = pair.resolver;
|
|
568
|
+
resolver.resolve({
|
|
569
|
+
data: resource
|
|
570
|
+
});
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
if (included.length > 0) {
|
|
575
|
+
store._push({
|
|
576
|
+
data: null,
|
|
577
|
+
included
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
if (snapshotsById.size === 0) {
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// reject missing records
|
|
585
|
+
let rejected = [];
|
|
586
|
+
snapshotsById.forEach(snapshots => {
|
|
587
|
+
rejected.push(...snapshots);
|
|
588
|
+
});
|
|
589
|
+
warn('Ember Data expected to find records with the following ids in the adapter response from findMany but they were missing: [ "' + [...snapshotsById.values()].map(r => r[0].id).join('", "') + '" ]', {
|
|
590
|
+
id: 'ds.store.missing-records-from-adapter'
|
|
591
|
+
});
|
|
592
|
+
rejectFetchedItems(fetchMap, rejected);
|
|
593
|
+
}
|
|
594
|
+
function _fetchRecord(store, fetchItem) {
|
|
595
|
+
let identifier = fetchItem.identifier;
|
|
596
|
+
let modelName = identifier.type;
|
|
597
|
+
let adapter = store.adapterFor(modelName);
|
|
598
|
+
assert(`You tried to find a record but you have no adapter (for ${modelName})`, adapter);
|
|
599
|
+
assert(`You tried to find a record but your adapter (for ${modelName}) does not implement 'findRecord'`, typeof adapter.findRecord === 'function');
|
|
600
|
+
let snapshot = store._instanceCache.createSnapshot(identifier, fetchItem.options);
|
|
601
|
+
let klass = store.modelFor(identifier.type);
|
|
602
|
+
let id = identifier.id;
|
|
603
|
+
let label = `DS: Handle Adapter#findRecord of '${modelName}' with id: '${id}'`;
|
|
604
|
+
let promise = guardDestroyedStore(resolve().then(() => {
|
|
605
|
+
return adapter.findRecord(store, klass, identifier.id, snapshot);
|
|
606
|
+
}), store, label);
|
|
607
|
+
promise = promise.then(adapterPayload => {
|
|
608
|
+
assert(`You made a 'findRecord' request for a '${modelName}' with id '${id}', but the adapter's response did not have any data`, !!payloadIsNotBlank(adapterPayload));
|
|
609
|
+
let serializer = store.serializerFor(modelName);
|
|
610
|
+
let payload = normalizeResponseHelper(serializer, store, klass, adapterPayload, id, 'findRecord');
|
|
611
|
+
assert(`Ember Data expected the primary data returned from a 'findRecord' response to be an object but instead it found an array.`, !Array.isArray(payload.data));
|
|
612
|
+
assert(`The 'findRecord' request for ${modelName}:${id} resolved indicating success but contained no primary data. To indicate a 404 not found you should either reject the promise returned by the adapter's findRecord method or throw a NotFoundError.`, 'data' in payload && payload.data !== null && typeof payload.data === 'object');
|
|
613
|
+
warn(`You requested a record of type '${modelName}' with id '${id}' but the adapter returned a payload with primary data having an id of '${payload.data.id}'. Use 'store.findRecord()' when the requested id is the same as the one returned by the adapter. In other cases use 'store.queryRecord()' instead.`, coerceId(payload.data.id) === coerceId(id), {
|
|
614
|
+
id: 'ds.store.findRecord.id-mismatch'
|
|
615
|
+
});
|
|
616
|
+
return payload;
|
|
617
|
+
});
|
|
618
|
+
fetchItem.resolver.resolve(promise);
|
|
619
|
+
}
|
|
620
|
+
function _processCoalescedGroup(store, fetchMap, group, adapter, modelName) {
|
|
621
|
+
if (group.length > 1) {
|
|
622
|
+
_findMany(store, adapter, modelName, group).then(payloads => {
|
|
623
|
+
handleFoundRecords(store, fetchMap, group, payloads);
|
|
624
|
+
}).catch(error => {
|
|
625
|
+
rejectFetchedItems(fetchMap, group, error);
|
|
626
|
+
});
|
|
627
|
+
} else if (group.length === 1) {
|
|
628
|
+
_fetchRecord(store, fetchMap.get(group[0]));
|
|
629
|
+
} else {
|
|
630
|
+
assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
function _flushPendingFetchForType(store, pendingFetchItems, modelName) {
|
|
634
|
+
let adapter = store.adapterFor(modelName);
|
|
635
|
+
let shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests;
|
|
636
|
+
let totalItems = pendingFetchItems.length;
|
|
637
|
+
if (shouldCoalesce) {
|
|
638
|
+
let snapshots = new Array(totalItems);
|
|
639
|
+
let fetchMap = new Map();
|
|
640
|
+
for (let i = 0; i < totalItems; i++) {
|
|
641
|
+
let fetchItem = pendingFetchItems[i];
|
|
642
|
+
snapshots[i] = store._instanceCache.createSnapshot(fetchItem.identifier, fetchItem.options);
|
|
643
|
+
fetchMap.set(snapshots[i], fetchItem);
|
|
644
|
+
}
|
|
645
|
+
let groups;
|
|
646
|
+
if (adapter.groupRecordsForFindMany) {
|
|
647
|
+
groups = adapter.groupRecordsForFindMany(store, snapshots);
|
|
648
|
+
} else {
|
|
649
|
+
groups = [snapshots];
|
|
650
|
+
}
|
|
651
|
+
for (let i = 0, l = groups.length; i < l; i++) {
|
|
652
|
+
_processCoalescedGroup(store, fetchMap, groups[i], adapter, modelName);
|
|
653
|
+
}
|
|
654
|
+
} else {
|
|
655
|
+
for (let i = 0; i < totalItems; i++) {
|
|
656
|
+
_fetchRecord(store, pendingFetchItems[i]);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
function _flushPendingSave(store, pending) {
|
|
661
|
+
const {
|
|
662
|
+
snapshot,
|
|
663
|
+
resolver,
|
|
664
|
+
identifier,
|
|
665
|
+
options
|
|
666
|
+
} = pending;
|
|
667
|
+
const adapter = store.adapterFor(identifier.type);
|
|
668
|
+
const operation = options[SaveOp];
|
|
669
|
+
let modelName = snapshot.modelName;
|
|
670
|
+
let modelClass = store.modelFor(modelName);
|
|
671
|
+
const record = store._instanceCache.getRecord(identifier);
|
|
672
|
+
assert(`You tried to update a record but you have no adapter (for ${modelName})`, adapter);
|
|
673
|
+
assert(`You tried to update a record but your adapter (for ${modelName}) does not implement '${operation}'`, typeof adapter[operation] === 'function');
|
|
674
|
+
let promise = resolve().then(() => adapter[operation](store, modelClass, snapshot));
|
|
675
|
+
let serializer = store.serializerFor(modelName);
|
|
676
|
+
assert(`Your adapter's '${operation}' method must return a value, but it returned 'undefined'`, promise !== undefined);
|
|
677
|
+
|
|
678
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
|
679
|
+
promise = _guard(guardDestroyedStore(promise, store, isDevelopingApp() ? `DS: Extract and notify about ${operation} completion of ${identifier.lid}` : ''),
|
|
680
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
|
681
|
+
_bind(_objectIsAlive, record));
|
|
682
|
+
promise = promise.then(adapterPayload => {
|
|
683
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
|
684
|
+
if (!_objectIsAlive(record)) {
|
|
685
|
+
if (macroCondition(getOwnConfig().deprecations.DEPRECATE_RSVP_PROMISE)) {
|
|
686
|
+
deprecate(`A Promise while saving ${modelName} did not resolve by the time your model was destroyed. This will error in a future release.`, false, {
|
|
687
|
+
id: 'ember-data:rsvp-unresolved-async',
|
|
688
|
+
until: '5.0',
|
|
689
|
+
for: '@ember-data/store',
|
|
690
|
+
since: {
|
|
691
|
+
available: '4.5',
|
|
692
|
+
enabled: '4.5'
|
|
693
|
+
}
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
if (adapterPayload) {
|
|
698
|
+
return normalizeResponseHelper(serializer, store, modelClass, adapterPayload, snapshot.id, operation);
|
|
699
|
+
}
|
|
700
|
+
});
|
|
701
|
+
resolver.resolve(promise);
|
|
702
|
+
}
|
|
703
|
+
export { FetchManager as F, SnapshotRecordArray as S, SaveOp as a, assertIdentifierHasId as b, guardDestroyedStore as g, normalizeResponseHelper as n };
|