-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
store.js
3013 lines (2429 loc) · 96.4 KB
/
store.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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
@module ember-data
*/
import { A } from '@ember/array';
import { copy } from '@ember/object/internals';
import EmberError from '@ember/error';
import MapWithDefault from './map-with-default';
import { run as emberRun } from '@ember/runloop';
import { set, get, computed } from '@ember/object';
import RSVP from 'rsvp';
import Service from '@ember/service';
import { typeOf, isPresent, isNone } from '@ember/utils';
import Ember from 'ember';
import { InvalidError } from '../adapters/errors';
import { instrument } from 'ember-data/-debug';
import { assert, deprecate, warn, inspect } from '@ember/debug';
import { DEBUG } from '@glimmer/env';
import Model from './model/model';
import normalizeModelName from "./normalize-model-name";
import IdentityMap from './identity-map';
import {
promiseArray,
promiseObject
} from "./promise-proxies";
import {
_bind,
_guard,
_objectIsAlive
} from "./store/common";
import { normalizeResponseHelper } from "./store/serializer-response";
import { serializerForAdapter } from "./store/serializers";
import RelationshipPayloadsManager from './relationships/relationship-payloads-manager';
import {
_find,
_findMany,
_findHasMany,
_findBelongsTo,
_findAll,
_query,
_queryRecord
} from "./store/finders";
import { getOwner } from '../utils';
import coerceId from "./coerce-id";
import RecordArrayManager from "./record-array-manager";
import InternalModel from "./model/internal-model";
const badIdFormatAssertion = '`id` passed to `findRecord()` has to be non-empty string or number';
const {
_Backburner: Backburner,
ENV
} = Ember;
const { Promise } = RSVP;
//Get the materialized model from the internalModel/promise that returns
//an internal model and return it in a promiseObject. Useful for returning
//from find methods
function promiseRecord(internalModelPromise, label) {
let toReturn = internalModelPromise.then(internalModel => internalModel.getRecord());
return promiseObject(toReturn, label);
}
let Store;
// Implementors Note:
//
// The variables in this file are consistently named according to the following
// scheme:
//
// * +id+ means an identifier managed by an external source, provided inside
// the data provided by that source. These are always coerced to be strings
// before being used internally.
// * +clientId+ means a transient numerical identifier generated at runtime by
// the data store. It is important primarily because newly created objects may
// not yet have an externally generated id.
// * +internalModel+ means a record internalModel object, which holds metadata about a
// record, even if it has not yet been fully materialized.
// * +type+ means a DS.Model.
const {
_generateId,
_internalModelForId,
_load,
_modelForMixin,
_pushInternalModel,
_setupRelationships,
adapterFor,
_buildInternalModel,
_didUpdateAll,
modelFactoryFor,
modelFor,
normalize,
peekAll,
peekRecord,
serializerFor,
_internalModelsFor
} = heimdall.registerMonitor('store',
'_generateId',
'_internalModelForId',
'_load',
'_modelForMixin',
'_pushInternalModel',
'_setupRelationships',
'adapterFor',
'_buildInternalModel',
'_didUpdateAll',
'modelFactoryFor',
'modelFor',
'normalize',
'peekAll',
'peekRecord',
'serializerFor',
'_internalModelsFor'
);
/**
The store contains all of the data for records loaded from the server.
It is also responsible for creating instances of `DS.Model` that wrap
the individual data for a record, so that they can be bound to in your
Handlebars templates.
Define your application's store like this:
```app/services/store.js
import DS from 'ember-data';
export default DS.Store.extend({
});
```
Most Ember.js applications will only have a single `DS.Store` that is
automatically created by their `Ember.Application`.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use `DS.Store`'s `findRecord()` method:
```javascript
store.findRecord('person', 123).then(function (person) {
});
```
By default, the store will talk to your backend using a standard
REST mechanism. You can customize how the store talks to your
backend by specifying a custom adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
});
```
You can learn more about writing a custom adapter by reading the `DS.Adapter`
documentation.
### Store createRecord() vs. push() vs. pushPayload()
The store provides multiple ways to create new record objects. They have
some subtle differences in their use which are detailed below:
[createRecord](#method_createRecord) is used for creating new
records on the client side. This will return a new record in the
`created.uncommitted` state. In order to persist this record to the
backend you will need to call `record.save()`.
[push](#method_push) is used to notify Ember Data's store of new or
updated records that exist in the backend. This will return a record
in the `loaded.saved` state. The primary use-case for `store#push` is
to notify Ember Data about record updates (full or partial) that happen
outside of the normal adapter methods (for example
[SSE](http://dev.w3.org/html5/eventsource/) or [Web
Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)).
[pushPayload](#method_pushPayload) is a convenience wrapper for
`store#push` that will deserialize payloads if the
Serializer implements a `pushPayload` method.
Note: When creating a new record using any of the above methods
Ember Data will update `DS.RecordArray`s such as those returned by
`store#peekAll()` or `store#findAll()`. This means any
data bindings or computed properties that depend on the RecordArray
will automatically be synced to include the new or updated record
values.
@class Store
@namespace DS
@extends Ember.Service
*/
Store = Service.extend({
/**
@method init
@private
*/
init() {
this._super(...arguments);
this._backburner = new Backburner(['normalizeRelationships', 'syncRelationships', 'finished']);
// internal bookkeeping; not observable
this.recordArrayManager = new RecordArrayManager({ store: this });
this._identityMap = new IdentityMap();
this._pendingSave = [];
this._modelFactoryCache = Object.create(null);
this._relationshipsPayloads = new RelationshipPayloadsManager(this);
/*
Ember Data uses several specialized micro-queues for organizing
and coalescing similar async work.
These queues are currently controlled by a flush scheduled into
ember-data's custom backburner instance.
*/
// used for coalescing record save requests
this._pendingSave = [];
// used for coalescing relationship updates
this._updatedRelationships = [];
// used for coalescing relationship setup needs
this._pushedInternalModels = [];
// used for coalescing internal model updates
this._updatedInternalModels = [];
// used to keep track of all the find requests that need to be coalesced
this._pendingFetch = new MapWithDefault({ defaultValue() { return []; } });
this._adapterCache = Object.create(null);
this._serializerCache = Object.create(null);
},
/**
The default adapter to use to communicate to a backend server or
other persistence layer. This will be overridden by an application
adapter if present.
If you want to specify `app/adapters/custom.js` as a string, do:
```js
import DS from 'ember-data';
export default DS.Store.extend({
adapter: 'custom',
});
```
@property adapter
@default '-json-api'
@type {String}
*/
adapter: '-json-api',
/**
Returns a JSON representation of the record using a custom
type-specific serializer, if one exists.
The available options are:
* `includeId`: `true` if the record's ID should be included in
the JSON representation
@method serialize
@private
@deprecated
@param {DS.Model} record the record to serialize
@param {Object} options an options hash
*/
serialize(record, options) {
deprecate('Use of store.serialize is deprecated, use record.serialize instead.', false, {
id: 'ds.store.serialize',
until: '3.0'
});
let snapshot = record._internalModel.createSnapshot();
return snapshot.serialize(options);
},
/**
This property returns the adapter, after resolving a possible
string key.
If the supplied `adapter` was a class, or a String property
path resolved to a class, this property will instantiate the
class.
This property is cacheable, so the same instance of a specified
adapter class should be used for the lifetime of the store.
@property defaultAdapter
@private
@return DS.Adapter
*/
defaultAdapter: computed('adapter', function() {
let adapter = get(this, 'adapter');
assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name', typeof adapter === 'string');
return this.adapterFor(adapter);
}),
// .....................
// . CREATE NEW RECORD .
// .....................
/**
Create a new record in the current store. The properties passed
to this method are set on the newly created record.
To create a new instance of a `Post`:
```js
store.createRecord('post', {
title: 'Rails is omakase'
});
```
To create a new instance of a `Post` that has a relationship with a `User` record:
```js
let user = this.store.peekRecord('user', 1);
store.createRecord('post', {
title: 'Rails is omakase',
user: user
});
```
@method createRecord
@param {String} modelName
@param {Object} inputProperties a hash of properties to set on the
newly created record.
@return {DS.Model} record
*/
createRecord(modelName, inputProperties) {
assert(`You need to pass a model name to the store's createRecord method`, isPresent(modelName));
assert(`Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, typeof modelName === 'string');
let normalizedModelName = normalizeModelName(modelName);
let properties = copy(inputProperties) || Object.create(null);
// If the passed properties do not include a primary key,
// give the adapter an opportunity to generate one. Typically,
// client-side ID generators will use something like uuid.js
// to avoid conflicts.
if (isNone(properties.id)) {
properties.id = this._generateId(normalizedModelName, properties);
}
// Coerce ID to a string
properties.id = coerceId(properties.id);
let internalModel = this._buildInternalModel(normalizedModelName, properties.id);
internalModel.loadedData();
let record = internalModel.getRecord();
record.setProperties(properties);
// TODO @runspired this should also be coalesced into some form of internalModel.setState()
internalModel.eachRelationship((key, descriptor) => {
if (properties[key] !== undefined) {
internalModel._relationships.get(key).setHasData(true);
}
});
return record;
},
/**
If possible, this method asks the adapter to generate an ID for
a newly created record.
@method _generateId
@private
@param {String} modelName
@param {Object} properties from the new record
@return {String} if the adapter can generate one, an ID
*/
_generateId(modelName, properties) {
heimdall.increment(_generateId);
let adapter = this.adapterFor(modelName);
if (adapter && adapter.generateIdForRecord) {
return adapter.generateIdForRecord(this, modelName, properties);
}
return null;
},
// .................
// . DELETE RECORD .
// .................
/**
For symmetry, a record can be deleted via the store.
Example
```javascript
let post = store.createRecord('post', {
title: 'Rails is omakase'
});
store.deleteRecord(post);
```
@method deleteRecord
@param {DS.Model} record
*/
deleteRecord(record) {
record.deleteRecord();
},
/**
For symmetry, a record can be unloaded via the store.
This will cause the record to be destroyed and freed up for garbage collection.
Example
```javascript
store.findRecord('post', 1).then(function(post) {
store.unloadRecord(post);
});
```
@method unloadRecord
@param {DS.Model} record
*/
unloadRecord(record) {
record.unloadRecord();
},
// ................
// . FIND RECORDS .
// ................
/**
@method find
@param {String} modelName
@param {String|Integer} id
@param {Object} options
@return {Promise} promise
@private
*/
find(modelName, id, options) {
// The default `model` hook in Route calls `find(modelName, id)`,
// that's why we have to keep this method around even though `findRecord` is
// the public way to get a record by modelName and id.
assert(`Using store.find(type) has been removed. Use store.findAll(modelName) to retrieve all records for a given type.`, arguments.length !== 1);
assert(`Calling store.find(modelName, id, { preload: preload }) is no longer supported. Use store.findRecord(modelName, id, { preload: preload }) instead.`, !options);
assert(`You need to pass the model name and id to the store's find method`, arguments.length === 2);
assert(`You cannot pass '${id}' as id to the store's find method`, typeof id === 'string' || typeof id === 'number');
assert(`Calling store.find() with a query object is no longer supported. Use store.query() instead.`, typeof id !== 'object');
assert(`Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, typeof modelName === 'string');
return this.findRecord(modelName, id);
},
/**
This method returns a record for a given type and id combination.
The `findRecord` method will always resolve its promise with the same
object for a given type and `id`.
The `findRecord` method will always return a **promise** that will be
resolved with the record.
Example
```app/routes/post.js
import Route from '@ember/routing/route';
export default Route.extend({
model(params) {
return this.store.findRecord('post', params.post_id);
}
});
```
If the record is not yet available, the store will ask the adapter's `find`
method to find the necessary data. If the record is already present in the
store, it depends on the reload behavior _when_ the returned promise
resolves.
### Preloading
You can optionally `preload` specific attributes and relationships that you know of
by passing them via the passed `options`.
For example, if your Ember route looks like `/posts/1/comments/2` and your API route
for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment
without fetching the post you can pass in the post to the `findRecord` call:
```javascript
store.findRecord('comment', 2, { preload: { post: 1 } });
```
If you have access to the post model you can also pass the model itself:
```javascript
store.findRecord('post', 1).then(function (myPostModel) {
store.findRecord('comment', 2, { post: myPostModel });
});
```
### Reloading
The reload behavior is configured either via the passed `options` hash or
the result of the adapter's `shouldReloadRecord`.
If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates
to `true`, then the returned promise resolves once the adapter returns
data, regardless if the requested record is already in the store:
```js
store.push({
data: {
id: 1,
type: 'post',
revision: 1
}
});
// adapter#findRecord resolves with
// [
// {
// id: 1,
// type: 'post',
// revision: 2
// }
// ]
store.findRecord('post', 1, { reload: true }).then(function(post) {
post.get('revision'); // 2
});
```
If no reload is indicated via the abovementioned ways, then the promise
immediately resolves with the cached version in the store.
### Background Reloading
Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`,
then a background reload is started, which updates the records' data, once
it is available:
```js
// app/adapters/post.js
import ApplicationAdapter from "./application";
export default ApplicationAdapter.extend({
shouldReloadRecord(store, snapshot) {
return false;
},
shouldBackgroundReloadRecord(store, snapshot) {
return true;
}
});
// ...
store.push({
data: {
id: 1,
type: 'post',
revision: 1
}
});
let blogPost = store.findRecord('post', 1).then(function(post) {
post.get('revision'); // 1
});
// later, once adapter#findRecord resolved with
// [
// {
// id: 1,
// type: 'post',
// revision: 2
// }
// ]
blogPost.get('revision'); // 2
```
If you would like to force or prevent background reloading, you can set a
boolean value for `backgroundReload` in the options object for
`findRecord`.
```app/routes/post/edit.js
import Route from '@ember/routing/route';
export default Route.extend({
model(params) {
return this.store.findRecord('post', params.post_id, { backgroundReload: false });
}
});
```
If you pass an object on the `adapterOptions` property of the options
argument it will be passed to you adapter via the snapshot
```app/routes/post/edit.js
import Route from '@ember/routing/route';
export default Route.extend({
model(params) {
return this.store.findRecord('post', params.post_id, {
adapterOptions: { subscribe: false }
});
}
});
```
```app/adapters/post.js
import MyCustomAdapter from './custom-adapter';
export default MyCustomAdapter.extend({
findRecord(store, type, id, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
});
```
See [peekRecord](#method_peekRecord) to get the cached version of a record.
### Retrieving Related Model Records
If you use an adapter such as Ember's default
[`JSONAPIAdapter`](https://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html)
that supports the [JSON API specification](http://jsonapi.org/) and if your server
endpoint supports the use of an
['include' query parameter](http://jsonapi.org/format/#fetching-includes),
you can use `findRecord()` to automatically retrieve additional records related to
the one you request by supplying an `include` parameter in the `options` object.
For example, given a `post` model that has a `hasMany` relationship with a `comment`
model, when we retrieve a specific post we can have the server also return that post's
comments in the same request:
```app/routes/post.js
import Route from '@ember/routing/route';
export default Route.extend({
model(params) {
return this.store.findRecord('post', params.post_id, { include: 'comments' });
}
});
```
In this case, the post's comments would then be available in your template as
`model.comments`.
Multiple relationships can be requested using an `include` parameter consisting of a
comma-separated list (without white-space) while nested relationships can be specified
using a dot-separated sequence of relationship names. So to request both the post's
comments and the authors of those comments the request would look like this:
```app/routes/post.js
import Route from '@ember/routing/route';
export default Route.extend({
model(params) {
return this.store.findRecord('post', params.post_id, { include: 'comments,comments.author' });
}
});
```
@since 1.13.0
@method findRecord
@param {String} modelName
@param {(String|Integer)} id
@param {Object} options
@return {Promise} promise
*/
findRecord(modelName, id, options) {
assert(`You need to pass a model name to the store's findRecord method`, isPresent(modelName));
assert(`Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, typeof modelName === 'string');
assert(badIdFormatAssertion, (typeof id === 'string' && id.length > 0) || (typeof id === 'number' && !isNaN(id)));
let normalizedModelName = normalizeModelName(modelName);
let internalModel = this._internalModelForId(normalizedModelName, id);
options = options || {};
if (!this.hasRecordForId(normalizedModelName, id)) {
return this._findByInternalModel(internalModel, options);
}
let fetchedInternalModel = this._findRecord(internalModel, options);
return promiseRecord(fetchedInternalModel, `DS: Store#findRecord ${normalizedModelName} with id: ${id}`);
},
_findRecord(internalModel, options) {
// Refetch if the reload option is passed
if (options.reload) {
return this._scheduleFetch(internalModel, options);
}
let snapshot = internalModel.createSnapshot(options);
let adapter = this.adapterFor(internalModel.modelName);
// Refetch the record if the adapter thinks the record is stale
if (adapter.shouldReloadRecord(this, snapshot)) {
return this._scheduleFetch(internalModel, options);
}
if (options.backgroundReload === false) {
return Promise.resolve(internalModel);
}
// Trigger the background refetch if backgroundReload option is passed
if (options.backgroundReload || adapter.shouldBackgroundReloadRecord(this, snapshot)) {
this._scheduleFetch(internalModel, options);
}
// Return the cached record
return Promise.resolve(internalModel);
},
_findByInternalModel(internalModel, options = {}) {
if (options.preload) {
internalModel.preloadData(options.preload);
}
let fetchedInternalModel = this._findEmptyInternalModel(internalModel, options);
return promiseRecord(fetchedInternalModel, `DS: Store#findRecord ${internalModel.modelName} with id: ${internalModel.id}`);
},
_findEmptyInternalModel(internalModel, options) {
if (internalModel.isEmpty()) {
return this._scheduleFetch(internalModel, options);
}
//TODO double check about reloading
if (internalModel.isLoading()) {
return internalModel._loadingPromise;
}
return Promise.resolve(internalModel);
},
/**
This method makes a series of requests to the adapter's `find` method
and returns a promise that resolves once they are all loaded.
@private
@method findByIds
@param {String} modelName
@param {Array} ids
@return {Promise} promise
*/
findByIds(modelName, ids) {
assert(`You need to pass a model name to the store's findByIds method`, isPresent(modelName));
assert(`Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`, typeof modelName === 'string');
let promises = new Array(ids.length);
let normalizedModelName = normalizeModelName(modelName);
for (let i = 0; i < ids.length; i++) {
promises[i] = this.findRecord(normalizedModelName, ids[i]);
}
return promiseArray(RSVP.all(promises).then(A, null, `DS: Store#findByIds of ${normalizedModelName} complete`));
},
/**
This method is called by `findRecord` if it discovers that a particular
type/id pair hasn't been loaded yet to kick off a request to the
adapter.
@method _fetchRecord
@private
@param {InternalModel} internalModel model
@return {Promise} promise
*/
_fetchRecord(internalModel, options) {
let modelName = internalModel.modelName;
let adapter = this.adapterFor(modelName);
assert(`You tried to find a record but you have no adapter (for ${modelName})`, adapter);
assert(`You tried to find a record but your adapter (for ${modelName}) does not implement 'findRecord'`, typeof adapter.findRecord === 'function');
return _find(adapter, this, internalModel.type, internalModel.id, internalModel, options);
},
_scheduleFetchMany(internalModels) {
let fetches = new Array(internalModels.length);
for (let i = 0; i < internalModels.length; i++) {
fetches[i] = this._scheduleFetch(internalModels[i]);
}
return Promise.all(fetches);
},
_scheduleFetch(internalModel, options) {
if (internalModel._loadingPromise) {
return internalModel._loadingPromise;
}
let { id, modelName } = internalModel;
let resolver = RSVP.defer(`Fetching ${modelName}' with id: ${id}`);
let pendingFetchItem = {
internalModel,
resolver,
options
};
let promise = resolver.promise;
internalModel.loadingData(promise);
if (this._pendingFetch.size === 0) {
emberRun.schedule('afterRender', this, this.flushAllPendingFetches);
}
this._pendingFetch.get(modelName).push(pendingFetchItem);
return promise;
},
flushAllPendingFetches() {
if (this.isDestroyed || this.isDestroying) {
return;
}
this._pendingFetch.forEach(this._flushPendingFetchForType, this);
this._pendingFetch.clear();
},
_flushPendingFetchForType(pendingFetchItems, modelName) {
let store = this;
let adapter = store.adapterFor(modelName);
let shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests;
let totalItems = pendingFetchItems.length;
let internalModels = new Array(totalItems);
let seeking = Object.create(null);
for (let i = 0; i < totalItems; i++) {
let pendingItem = pendingFetchItems[i];
let internalModel = pendingItem.internalModel;
internalModels[i] = internalModel;
seeking[internalModel.id] = pendingItem;
}
for (let i = 0; i < totalItems; i++) {
let internalModel = internalModels[i];
// We may have unloaded the record after scheduling this fetch, in which
// case we must cancel the destroy. This is because we require a record
// to build a snapshot. This is not fundamental: this cancelation code
// can be removed when snapshots can be created for internal models that
// have no records.
if (internalModel.hasScheduledDestroy()) {
internalModels[i].cancelDestroy();
}
}
function _fetchRecord(recordResolverPair) {
let recordFetch = store._fetchRecord(
recordResolverPair.internalModel,
recordResolverPair.options
); // TODO adapter options
recordResolverPair.resolver.resolve(recordFetch);
}
function handleFoundRecords(foundInternalModels, expectedInternalModels) {
// resolve found records
let found = Object.create(null);
for (let i = 0, l = foundInternalModels.length; i < l; i++) {
let internalModel = foundInternalModels[i];
let pair = seeking[internalModel.id];
found[internalModel.id] = internalModel;
if (pair) {
let resolver = pair.resolver;
resolver.resolve(internalModel);
}
}
// reject missing records
let missingInternalModels = [];
for (let i = 0, l = expectedInternalModels.length; i < l; i++) {
let internalModel = expectedInternalModels[i];
if (!found[internalModel.id]) {
missingInternalModels.push(internalModel);
}
}
if (missingInternalModels.length) {
warn('Ember Data expected to find records with the following ids in the adapter response but they were missing: ' + inspect(missingInternalModels.map(r => r.id)), false, {
id: 'ds.store.missing-records-from-adapter'
});
rejectInternalModels(missingInternalModels);
}
}
function rejectInternalModels(internalModels, error) {
for (let i = 0, l = internalModels.length; i < l; i++) {
let internalModel = internalModels[i];
let pair = seeking[internalModel.id];
if (pair) {
pair.resolver.reject(error || new Error(`Expected: '${internalModel}' to be present in the adapter provided payload, but it was not found.`));
}
}
}
if (shouldCoalesce) {
// TODO: Improve records => snapshots => records => snapshots
//
// We want to provide records to all store methods and snapshots to all
// adapter methods. To make sure we're doing that we're providing an array
// of snapshots to adapter.groupRecordsForFindMany(), which in turn will
// return grouped snapshots instead of grouped records.
//
// But since the _findMany() finder is a store method we need to get the
// records from the grouped snapshots even though the _findMany() finder
// will once again convert the records to snapshots for adapter.findMany()
let snapshots = new Array(totalItems);
for (let i = 0; i < totalItems; i++) {
snapshots[i] = internalModels[i].createSnapshot();
}
let groups = adapter.groupRecordsForFindMany(this, snapshots);
for (var i = 0, l = groups.length; i < l; i++) {
var group = groups[i];
var totalInGroup = groups[i].length;
var ids = new Array(totalInGroup);
var groupedInternalModels = new Array(totalInGroup);
for (var j = 0; j < totalInGroup; j++) {
var internalModel = group[j]._internalModel;
groupedInternalModels[j] = internalModel;
ids[j] = internalModel.id;
}
if (totalInGroup > 1) {
(function(groupedInternalModels) {
_findMany(adapter, store, modelName, ids, groupedInternalModels)
.then(function(foundInternalModels) {
handleFoundRecords(foundInternalModels, groupedInternalModels);
})
.catch(function(error) {
rejectInternalModels(groupedInternalModels, error);
});
}(groupedInternalModels));
} else if (ids.length === 1) {
var pair = seeking[groupedInternalModels[0].id];
_fetchRecord(pair);
} else {
assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false);
}
}
} else {
for (let i = 0; i < totalItems; i++) {
_fetchRecord(pendingFetchItems[i]);
}
}
},
/**
Get the reference for the specified record.
Example
```javascript
let userRef = store.getReference('user', 1);
// check if the user is loaded
let isLoaded = userRef.value() !== null;
// get the record of the reference (null if not yet available)
let user = userRef.value();
// get the identifier of the reference
if (userRef.remoteType() === 'id') {
let id = userRef.id();
}
// load user (via store.find)
userRef.load().then(...)
// or trigger a reload
userRef.reload().then(...)