forked from 418sec/js-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleStore.ts
2097 lines (2017 loc) · 71.9 KB
/
SimpleStore.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
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
import utils from './utils'
import { belongsToType, hasManyType, hasOneType } from './decorators'
import { Container, proxiedMapperMethods } from './Container'
import Collection from './Collection'
import { MapperOpts } from './Mapper'
import Schema from './Schema'
const DOMAIN = 'SimpleStore'
const proxiedCollectionMethods = [
'add',
'between',
'createIndex',
'filter',
'get',
'getAll',
'prune',
'query',
'toJSON',
'unsaved'
]
const ownMethodsForScoping = ['addToCache', 'cachedFind', 'cachedFindAll', 'cacheFind', 'cacheFindAll', 'hashQuery']
const cachedFn = function (name, hashOrId, opts) {
const cached = this._completedQueries[name][hashOrId]
if (utils.isFunction(cached)) {
return cached(name, hashOrId, opts)
}
return cached
}
export interface SimpleStoreOpts {
/**
* Whether to use the pending query if a `find` request for the specified
* record is currently underway. Can be set to `true`, `false`, or to a
* function that returns `true` or `false`.
*
* @default true
* @name SimpleStore#usePendingFind
* @since 3.0.0
* @type {boolean|Function}
*/
usePendingFind?: boolean | Function
/**
* Whether to use the pending query if a `findAll` request for the given query
* is currently underway. Can be set to `true`, `false`, or to a function that
* returns `true` or `false`.
*
* @default true
* @name SimpleStore#usePendingFindAll
* @since 3.0.0
* @type {boolean|Function}
*/
usePendingFindAll?: boolean | Function
}
const SIMPLESTORE_DEFAULTS = {
/**
* Whether to use the pending query if a `find` request for the specified
* record is currently underway. Can be set to `true`, `false`, or to a
* function that returns `true` or `false`.
*
* @default true
* @name SimpleStore#usePendingFind
* @since 3.0.0
* @type {boolean|Function}
*/
usePendingFind: true,
/**
* Whether to use the pending query if a `findAll` request for the given query
* is currently underway. Can be set to `true`, `false`, or to a function that
* returns `true` or `false`.
*
* @default true
* @name SimpleStore#usePendingFindAll
* @since 3.0.0
* @type {boolean|Function}
*/
usePendingFindAll: true
}
/**
* The `SimpleStore` class is an extension of {@link Container}. Not only does
* `SimpleStore` manage mappers, but also collections. `SimpleStore` implements the
* asynchronous {@link Mapper} methods, such as {@link Mapper#find} and
* {@link Mapper#create}. If you use the asynchronous `SimpleStore` methods
* instead of calling them directly on the mappers, then the results of the
* method calls will be inserted into the store's collections. You can think of
* a `SimpleStore` as an [Identity Map](https://en.wikipedia.org/wiki/Identity_map_pattern)
* for the [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)
* (the Mappers).
*
* ```javascript
* import { SimpleStore } from 'js-data';
* ```
*
* @example
* import { SimpleStore } from 'js-data';
* import { HttpAdapter } from 'js-data-http';
* const store = new SimpleStore();
*
* // SimpleStore#defineMapper returns a direct reference to the newly created
* // Mapper.
* const UserMapper = store.defineMapper('user');
*
* // SimpleStore#as returns the store scoped to a particular Mapper.
* const UserStore = store.as('user');
*
* // Call "find" on "UserMapper" (Stateless ORM)
* UserMapper.find(1).then((user) => {
* // retrieved a "user" record via the http adapter, but that's it
*
* // Call "find" on "store" targeting "user" (Stateful SimpleStore)
* return store.find('user', 1); // same as "UserStore.find(1)"
* }).then((user) => {
* // not only was a "user" record retrieved, but it was added to the
* // store's "user" collection
* const cachedUser = store.getCollection('user').get(1);
* console.log(user === cachedUser); // true
* });
*
* @class SimpleStore
* @extends Container
* @param {object} [opts] Configuration options. See {@link Container}.
* @param {boolean} [opts.collectionClass={@link Collection}] See {@link SimpleStore#collectionClass}.
* @param {boolean} [opts.debug=false] See {@link Component#debug}.
* @param {boolean|Function} [opts.usePendingFind=true] See {@link SimpleStore#usePendingFind}.
* @param {boolean|Function} [opts.usePendingFindAll=true] See {@link SimpleStore#usePendingFindAll}.
* @returns {SimpleStore}
* @see Container
* @since 3.0.0
* @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#SimpleStore","Components of JSData: SimpleStore"]
* @tutorial ["http://www.js-data.io/v3.0/docs/working-with-the-SimpleStore","Working with the SimpleStore"]
* @tutorial ["http://www.js-data.io/v3.0/docs/jsdata-and-the-browser","Notes on using JSData in the Browser"]
*/
export default class SimpleStore extends Container {
collectionClass: typeof Collection;
_collections: { [name: string]: Collection } = {};
_completedQueries = {};
_pendingQueries = {};
usePendingFind: boolean;
usePendingFindAll: boolean;
constructor (opts: SimpleStoreOpts = {}) {
super({ ...SIMPLESTORE_DEFAULTS, ...opts })
this.collectionClass = this.collectionClass || Collection
}
/**
* Internal method used to handle Mapper responses.
*
* @method SimpleStore#_end
* @private
* @param {string} name Name of the {@link Collection} to which to
* add the data.
* @param {object} result The result from a Mapper.
* @param {object} [opts] Configuration options.
* @returns {(Object|Array)} Result.
*/
_end (name, result, opts) {
let data = opts.raw ? result.data : result
if (data && utils.isFunction(this.addToCache)) {
data = this.addToCache(name, data, opts)
if (opts.raw) {
result.data = data
} else {
result = data
}
}
return result
}
/**
* Register a new event listener on this SimpleStore.
*
* Proxy for {@link Container#on}. If an event was emitted by a Mapper or
* Collection in the SimpleStore, then the name of the Mapper or Collection will
* be prepended to the arugments passed to the provided event handler.
*
* @example
* // Listen for all "afterCreate" events in a SimpleStore
* store.on('afterCreate', (mapperName, props, opts, result) => {
* console.log(mapperName); // "post"
* console.log(props.id); // undefined
* console.log(result.id); // 1234
* });
* store.create('post', { title: 'Modeling your data' }).then((post) => {
* console.log(post.id); // 1234
* });
*
* @example
* // Listen for the "add" event on a collection
* store.on('add', (mapperName, records) => {
* console.log(records); // [...]
* });
*
* @example
* // Listen for "change" events on a record
* store.on('change', (mapperName, record, changes) => {
* console.log(changes); // { changed: { title: 'Modeling your data' } }
* });
* post.title = 'Modeling your data';
*
* @method SimpleStore#on
* @param {string} event Name of event to subsribe to.
* @param {Function} listener Listener function to handle the event.
* @param {*} [ctx] Optional content in which to invoke the listener.
*/
/**
* Used to bind to events emitted by collections in this store.
*
* @method SimpleStore#_onCollectionEvent
* @private
* @param {string} name Name of the collection that emitted the event.
* @param {...*} [args] Args passed to {@link Collection#emit}.
*/
_onCollectionEvent (name, ...args) {
const type = args.shift()
this.emit(type, name, ...args)
}
/**
* This method takes the data received from {@link SimpleStore#find},
* {@link SimpleStore#findAll}, {@link SimpleStore#update}, etc., and adds the
* data to the store. _You don't need to call this method directly._
*
* If you're using the http adapter and your response data is in an unexpected
* format, you may need to override this method so the right data gets added
* to the store.
*
* @example
* const store = new SimpleStore({
* addToCache (mapperName, data, opts) {
* // Let's say for a particular Resource, response data is in a weird format
* if (name === 'comment') {
* // Re-assign the variable to add the correct records into the stores
* data = data.items;
* }
* // Now perform default behavior
* return SimpleStore.prototype.addToCache.call(this, mapperName, data, opts);
* }
* });
*
* @example
* // Extend using ES2015 class syntax.
* class MyStore extends SimpleStore {
* addToCache (mapperName, data, opts) {
* // Let's say for a particular Resource, response data is in a weird format
* if (name === 'comment') {
* // Re-assign the variable to add the correct records into the stores
* data = data.items;
* }
* // Now perform default behavior
* return super.addToCache(mapperName, data, opts);
* }
* }
* const store = new MyStore();
*
* @method SimpleStore#addToCache
* @param {string} name Name of the {@link Mapper} to target.
* @param {*} data Data from which data should be selected for add.
* @param {object} [opts] Configuration options.
*/
addToCache (name, data, opts) {
return this.getCollection(name).add(data, opts)
}
/**
* Return the store scoped to a particular mapper/collection pair.
*
* @example <caption>SimpleStore.as</caption>
* const JSData = require('js-data');
* const { SimpleStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new SimpleStore();
* const UserMapper = store.defineMapper('user');
* const UserStore = store.as('user');
*
* const user1 = store.createRecord('user', { name: 'John' });
* const user2 = UserStore.createRecord({ name: 'John' });
* const user3 = UserMapper.createRecord({ name: 'John' });
* console.log(user1 === user2);
* console.log(user2 === user3);
* console.log(user1 === user3);
*
* @method SimpleStore#as
* @param {string} name Name of the {@link Mapper}.
* @returns {Object} The store, scoped to a particular Mapper/Collection pair.
* @since 3.0.0
*/
as (name) {
const props: any = {}
const original = this
const methods = ownMethodsForScoping.concat(proxiedMapperMethods).concat(proxiedCollectionMethods)
methods.forEach(method => {
props[method] = {
writable: true,
value (...args) {
return original[method](name, ...args)
}
}
})
props.getMapper = {
writable: true,
value () {
return original.getMapper(name)
}
}
props.getCollection = {
writable: true,
value () {
return original.getCollection(name)
}
}
return Object.create(this, props)
}
/**
* Retrieve a cached `find` result, if any. This method is called during
* {@link SimpleStore#find} to determine if {@link Mapper#find} needs to be
* called. If this method returns `undefined` then {@link Mapper#find} will
* be called. Otherwise {@link SimpleStore#find} will immediately resolve with
* the return value of this method.
*
* When using {@link SimpleStore} in the browser, you can override this method
* to implement your own cache-busting strategy.
*
* @example
* const store = new SimpleStore({
* cachedFind (mapperName, id, opts) {
* // Let's say for a particular Resource, we always want to pull fresh from the server
* if (mapperName === 'schedule') {
* // Return undefined to trigger a Mapper#find call
* return;
* }
* // Otherwise perform default behavior
* return SimpleStore.prototype.cachedFind.call(this, mapperName, id, opts);
* }
* });
*
* @example
* // Extend using ES2015 class syntax.
* class MyStore extends SimpleStore {
* cachedFind (mapperName, id, opts) {
* // Let's say for a particular Resource, we always want to pull fresh from the server
* if (mapperName === 'schedule') {
* // Return undefined to trigger a Mapper#find call
* return;
* }
* // Otherwise perform default behavior
* return super.cachedFind(mapperName, id, opts);
* }
* }
* const store = new MyStore();
*
* @method SimpleStore#cachedFind
* @param {string} name The `name` argument passed to {@link SimpleStore#find}.
* @param {(string|number)} id The `id` argument passed to {@link SimpleStore#find}.
* @param {object} opts The `opts` argument passed to {@link SimpleStore#find}.
* @since 3.0.0
*/
cachedFind = cachedFn
/**
* Retrieve a cached `findAll` result, if any. This method is called during
* {@link SimpleStore#findAll} to determine if {@link Mapper#findAll} needs to be
* called. If this method returns `undefined` then {@link Mapper#findAll} will
* be called. Otherwise {@link SimpleStore#findAll} will immediately resolve with
* the return value of this method.
*
* When using {@link SimpleStore} in the browser, you can override this method
* to implement your own cache-busting strategy.
*
* @example
* const store = new SimpleStore({
* cachedFindAll (mapperName, hash, opts) {
* // Let's say for a particular Resource, we always want to pull fresh from the server
* if (mapperName === 'schedule') {
* // Return undefined to trigger a Mapper#findAll call
* return undefined;
* }
* // Otherwise perform default behavior
* return SimpleStore.prototype.cachedFindAll.call(this, mapperName, hash, opts);
* }
* });
*
* @example
* // Extend using ES2015 class syntax.
* class MyStore extends SimpleStore {
* cachedFindAll (mapperName, hash, opts) {
* // Let's say for a particular Resource, we always want to pull fresh from the server
* if (mapperName === 'schedule') {
* // Return undefined to trigger a Mapper#findAll call
* return undefined;
* }
* // Otherwise perform default behavior
* return super.cachedFindAll(mapperName, hash, opts);
* }
* }
* const store = new MyStore();
*
* @method SimpleStore#cachedFindAll
* @param {string} name The `name` argument passed to {@link SimpleStore#findAll}.
* @param {string} hash The result of calling {@link SimpleStore#hashQuery} on
* the `query` argument passed to {@link SimpleStore#findAll}.
* @param {object} opts The `opts` argument passed to {@link SimpleStore#findAll}.
* @since 3.0.0
*/
cachedFindAll = cachedFn
/**
* Mark a {@link Mapper#find} result as cached by adding an entry to
* {@link SimpleStore#_completedQueries}. By default, once a `find` entry is
* added it means subsequent calls to the same Resource with the same `id`
* argument will immediately resolve with the result of calling
* {@link SimpleStore#get} instead of delegating to {@link Mapper#find}.
*
* As part of implementing your own caching strategy, you may choose to
* override this method.
*
* @example
* const store = new SimpleStore({
* cacheFind (mapperName, data, id, opts) {
* // Let's say for a particular Resource, we always want to pull fresh from the server
* if (mapperName === 'schedule') {
* // Return without saving an entry to SimpleStore#_completedQueries
* return;
* }
* // Otherwise perform default behavior
* return SimpleStore.prototype.cacheFind.call(this, mapperName, data, id, opts);
* }
* });
*
* @example
* // Extend using ES2015 class syntax.
* class MyStore extends SimpleStore {
* cacheFind (mapperName, data, id, opts) {
* // Let's say for a particular Resource, we always want to pull fresh from the server
* if (mapperName === 'schedule') {
* // Return without saving an entry to SimpleStore#_completedQueries
* return;
* }
* // Otherwise perform default behavior
* return super.cacheFind(mapperName, data, id, opts);
* }
* }
* const store = new MyStore();
*
* @method SimpleStore#cacheFind
* @param {string} name The `name` argument passed to {@link SimpleStore#find}.
* @param {*} data The result to cache.
* @param {(string|number)} id The `id` argument passed to {@link SimpleStore#find}.
* @param {object} opts The `opts` argument passed to {@link SimpleStore#find}.
* @since 3.0.0
*/
cacheFind (name, data, id, opts) {
this._completedQueries[name][id] = (name, id, opts) => this.get(name, id)
}
/**
* Mark a {@link Mapper#findAll} result as cached by adding an entry to
* {@link SimpleStore#_completedQueries}. By default, once a `findAll` entry is
* added it means subsequent calls to the same Resource with the same `query`
* argument will immediately resolve with the result of calling
* {@link SimpleStore#filter} instead of delegating to {@link Mapper#findAll}.
*
* As part of implementing your own caching strategy, you may choose to
* override this method.
*
* @example
* const store = new SimpleStore({
* cachedFindAll (mapperName, data, hash, opts) {
* // Let's say for a particular Resource, we always want to pull fresh from the server
* if (mapperName === 'schedule') {
* // Return without saving an entry to SimpleStore#_completedQueries
* return;
* }
* // Otherwise perform default behavior.
* return SimpleStore.prototype.cachedFindAll.call(this, mapperName, data, hash, opts);
* }
* });
*
* @example
* // Extend using ES2015 class syntax.
* class MyStore extends SimpleStore {
* cachedFindAll (mapperName, data, hash, opts) {
* // Let's say for a particular Resource, we always want to pull fresh from the server
* if (mapperName === 'schedule') {
* // Return without saving an entry to SimpleStore#_completedQueries
* return;
* }
* // Otherwise perform default behavior.
* return super.cachedFindAll(mapperName, data, hash, opts);
* }
* }
* const store = new MyStore();
*
* @method SimpleStore#cacheFindAll
* @param {string} name The `name` argument passed to {@link SimpleStore#findAll}.
* @param {*} data The result to cache.
* @param {string} hash The result of calling {@link SimpleStore#hashQuery} on
* the `query` argument passed to {@link SimpleStore#findAll}.
* @param {object} opts The `opts` argument passed to {@link SimpleStore#findAll}.
* @since 3.0.0
*/
cacheFindAll (name, data, hash, opts) {
this._completedQueries[name][hash] = (name, hash, opts) => this.filter(name, utils.fromJson(hash))
}
/**
* Remove __all__ records from the in-memory store and reset
* {@link SimpleStore#_completedQueries}.
*
* @method SimpleStore#clear
* @returns {Object} Object containing all records that were in the store.
* @see SimpleStore#remove
* @see SimpleStore#removeAll
* @since 3.0.0
*/
clear () {
const removed = {}
utils.forOwn(this._collections, (collection, name) => {
removed[name] = collection.removeAll()
this._completedQueries[name] = {}
})
return removed
}
/**
* Fired during {@link SimpleStore#create}. See
* {@link SimpleStore~beforeCreateListener} for how to listen for this event.
*
* @event SimpleStore#beforeCreate
* @see SimpleStore~beforeCreateListener
* @see SimpleStore#create
*/
/**
* Callback signature for the {@link SimpleStore#event:beforeCreate} event.
*
* @example
* function onBeforeCreate (mapperName, props, opts) {
* // do something
* }
* store.on('beforeCreate', onBeforeCreate);
*
* @callback SimpleStore~beforeCreateListener
* @param {string} name The `name` argument received by {@link Mapper#beforeCreate}.
* @param {object} props The `props` argument received by {@link Mapper#beforeCreate}.
* @param {object} opts The `opts` argument received by {@link Mapper#beforeCreate}.
* @see SimpleStore#event:beforeCreate
* @see SimpleStore#create
* @since 3.0.0
*/
/**
* Fired during {@link SimpleStore#create}. See
* {@link SimpleStore~afterCreateListener} for how to listen for this event.
*
* @event SimpleStore#afterCreate
* @see SimpleStore~afterCreateListener
* @see SimpleStore#create
*/
/**
* Callback signature for the {@link SimpleStore#event:afterCreate} event.
*
* @example
* function onAfterCreate (mapperName, props, opts, result) {
* // do something
* }
* store.on('afterCreate', onAfterCreate);
*
* @callback SimpleStore~afterCreateListener
* @param {string} name The `name` argument received by {@link Mapper#afterCreate}.
* @param {object} props The `props` argument received by {@link Mapper#afterCreate}.
* @param {object} opts The `opts` argument received by {@link Mapper#afterCreate}.
* @param {object} result The `result` argument received by {@link Mapper#afterCreate}.
* @see SimpleStore#event:afterCreate
* @see SimpleStore#create
* @since 3.0.0
*/
/**
* Wrapper for {@link Mapper#create}. Adds the created record to the store.
*
* @example
* import { SimpleStore } from 'js-data';
* import { HttpAdapter } from 'js-data-http';
*
* const store = new SimpleStore();
* store.registerAdapter('http', new HttpAdapter(), { default: true });
*
* store.defineMapper('book');
*
* // Since this example uses the http adapter, we'll get something like:
* //
* // POST /book {"author_id":1234,...}
* store.create('book', {
* author_id: 1234,
* edition: 'First Edition',
* title: 'Respect your Data'
* }).then((book) => {
* console.log(book.id); // 120392
* console.log(book.title); // "Respect your Data"
* });
*
* @fires SimpleStore#beforeCreate
* @fires SimpleStore#afterCreate
* @fires SimpleStore#add
* @method SimpleStore#create
* @param {string} name Name of the {@link Mapper} to target.
* @param {object} record Passed to {@link Mapper#create}.
* @param {object} [opts] Passed to {@link Mapper#create}. See
* {@link Mapper#create} for more configuration options.
* @returns {Promise} Resolves with the result of the create.
* @since 3.0.0
*/
create (name, record, opts: any = {}) {
return super.create(name, record, opts).then(result => this._end(name, result, opts))
}
/**
* Fired during {@link SimpleStore#createMany}. See
* {@link SimpleStore~beforeCreateManyListener} for how to listen for this event.
*
* @event SimpleStore#beforeCreateMany
* @see SimpleStore~beforeCreateManyListener
* @see SimpleStore#createMany
*/
/**
* Callback signature for the {@link SimpleStore#event:beforeCreateMany} event.
*
* @example
* function onBeforeCreateMany (mapperName, records, opts) {
* // do something
* }
* store.on('beforeCreateMany', onBeforeCreateMany);
*
* @callback SimpleStore~beforeCreateManyListener
* @param {string} name The `name` argument received by {@link Mapper#beforeCreateMany}.
* @param {object} records The `records` argument received by {@link Mapper#beforeCreateMany}.
* @param {object} opts The `opts` argument received by {@link Mapper#beforeCreateMany}.
* @see SimpleStore#event:beforeCreateMany
* @see SimpleStore#createMany
* @since 3.0.0
*/
/**
* Fired during {@link SimpleStore#createMany}. See
* {@link SimpleStore~afterCreateManyListener} for how to listen for this event.
*
* @event SimpleStore#afterCreateMany
* @see SimpleStore~afterCreateManyListener
* @see SimpleStore#createMany
*/
/**
* Callback signature for the {@link SimpleStore#event:afterCreateMany} event.
*
* @example
* function onAfterCreateMany (mapperName, records, opts, result) {
* // do something
* }
* store.on('afterCreateMany', onAfterCreateMany);
*
* @callback SimpleStore~afterCreateManyListener
* @param {string} name The `name` argument received by {@link Mapper#afterCreateMany}.
* @param {object} records The `records` argument received by {@link Mapper#afterCreateMany}.
* @param {object} opts The `opts` argument received by {@link Mapper#afterCreateMany}.
* @param {object} result The `result` argument received by {@link Mapper#afterCreateMany}.
* @see SimpleStore#event:afterCreateMany
* @see SimpleStore#createMany
* @since 3.0.0
*/
/**
* Wrapper for {@link Mapper#createMany}. Adds the created records to the
* store.
*
* @example
* import { SimpleStore } from 'js-data';
* import { HttpAdapter } from 'js-data-http';
*
* const store = new SimpleStore();
* store.registerAdapter('http', new HttpAdapter(), { default: true });
*
* store.defineMapper('book');
*
* // Since this example uses the http adapter, we'll get something like:
* //
* // POST /book [{"author_id":1234,...},{...}]
* store.createMany('book', [{
* author_id: 1234,
* edition: 'First Edition',
* title: 'Respect your Data'
* }, {
* author_id: 1234,
* edition: 'Second Edition',
* title: 'Respect your Data'
* }]).then((books) => {
* console.log(books[0].id); // 142394
* console.log(books[0].title); // "Respect your Data"
* });
*
* @fires SimpleStore#beforeCreateMany
* @fires SimpleStore#afterCreateMany
* @fires SimpleStore#add
* @method SimpleStore#createMany
* @param {string} name Name of the {@link Mapper} to target.
* @param {array} records Passed to {@link Mapper#createMany}.
* @param {object} [opts] Passed to {@link Mapper#createMany}. See
* {@link Mapper#createMany} for more configuration options.
* @returns {Promise} Resolves with the result of the create.
* @since 3.0.0
*/
createMany (name, records, opts: any = {}) {
return super.createMany(name, records, opts).then(result => this._end(name, result, opts))
}
defineMapper (name, opts: MapperOpts = {}) {
const self = this
const mapper = super.defineMapper(name, opts)
self._pendingQueries[name] = {}
self._completedQueries[name] = {}
if (!mapper.relationList) Object.defineProperty(mapper, 'relationList', { value: [] })
const collectionOpts: any = {
// Make sure the collection has somewhere to store "added" timestamps
_added: {},
// Give the collection a reference to this SimpleStore
datastore: this,
// The mapper tied to the collection
mapper
}
if (opts && 'onConflict' in opts) {
collectionOpts.onConflict = opts.onConflict
}
// The SimpleStore uses a subclass of Collection that is "SimpleStore-aware"
const collection = (self._collections[name] = new self.collectionClass(null, collectionOpts))
const schema = mapper.schema || ({} as Schema)
const properties = schema.properties || {}
// TODO: Make it possible index nested properties?
utils.forOwn(properties, (opts, prop) => {
if (opts.indexed) {
collection.createIndex(prop)
}
})
// Create a secondary index on the "added" timestamps of records in the
// collection
collection.createIndex('addedTimestamps', ['$'], {
fieldGetter (obj) {
return collection._added[collection.recordId(obj)]
}
})
collection.on('all', (...args) => {
self._onCollectionEvent(name, ...args)
})
return mapper
}
/**
* Fired during {@link SimpleStore#destroy}. See
* {@link SimpleStore~beforeDestroyListener} for how to listen for this event.
*
* @event SimpleStore#beforeDestroy
* @see SimpleStore~beforeDestroyListener
* @see SimpleStore#destroy
*/
/**
* Callback signature for the {@link SimpleStore#event:beforeDestroy} event.
*
* @example
* function onBeforeDestroy (mapperName, id, opts) {
* // do something
* }
* store.on('beforeDestroy', onBeforeDestroy);
*
* @callback SimpleStore~beforeDestroyListener
* @param {string} name The `name` argument received by {@link Mapper#beforeDestroy}.
* @param {string|number} id The `id` argument received by {@link Mapper#beforeDestroy}.
* @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroy}.
* @see SimpleStore#event:beforeDestroy
* @see SimpleStore#destroy
* @since 3.0.0
*/
/**
* Fired during {@link SimpleStore#destroy}. See
* {@link SimpleStore~afterDestroyListener} for how to listen for this event.
*
* @event SimpleStore#afterDestroy
* @see SimpleStore~afterDestroyListener
* @see SimpleStore#destroy
*/
/**
* Callback signature for the {@link SimpleStore#event:afterDestroy} event.
*
* @example
* function onAfterDestroy (mapperName, id, opts, result) {
* // do something
* }
* store.on('afterDestroy', onAfterDestroy);
*
* @callback SimpleStore~afterDestroyListener
* @param {string} name The `name` argument received by {@link Mapper#afterDestroy}.
* @param {string|number} id The `id` argument received by {@link Mapper#afterDestroy}.
* @param {object} opts The `opts` argument received by {@link Mapper#afterDestroy}.
* @param {object} result The `result` argument received by {@link Mapper#afterDestroy}.
* @see SimpleStore#event:afterDestroy
* @see SimpleStore#destroy
* @since 3.0.0
*/
/**
* Wrapper for {@link Mapper#destroy}. Removes any destroyed record from the
* in-memory store. Clears out any {@link SimpleStore#_completedQueries} entries
* associated with the provided `id`.
*
* @example
* import { SimpleStore } from 'js-data';
* import { HttpAdapter } from 'js-data-http';
*
* const store = new SimpleStore();
* store.registerAdapter('http', new HttpAdapter(), { default: true });
*
* store.defineMapper('book');
*
* store.add('book', { id: 1234, title: 'Data Management is Hard' });
*
* // Since this example uses the http adapter, we'll get something like:
* //
* // DELETE /book/1234
* store.destroy('book', 1234).then(() => {
* // The book record is no longer in the in-memory store
* console.log(store.get('book', 1234)); // undefined
*
* return store.find('book', 1234);
* }).then((book) {
* // The book was deleted from the database too
* console.log(book); // undefined
* });
*
* @fires SimpleStore#beforeDestroy
* @fires SimpleStore#afterDestroy
* @fires SimpleStore#remove
* @method SimpleStore#destroy
* @param {string} name Name of the {@link Mapper} to target.
* @param {(string|number)} id Passed to {@link Mapper#destroy}.
* @param {object} [opts] Passed to {@link Mapper#destroy}. See
* {@link Mapper#destroy} for more configuration options.
* @returns {Promise} Resolves when the destroy operation completes.
* @since 3.0.0
*/
destroy (name, id, opts: any = {}) {
return super.destroy(name, id, opts).then(result => {
const record = this.getCollection(name).remove(id, opts)
if (opts.raw) {
result.data = record
} else {
result = record
}
delete this._pendingQueries[name][id]
delete this._completedQueries[name][id]
return result
})
}
/**
* Fired during {@link SimpleStore#destroyAll}. See
* {@link SimpleStore~beforeDestroyAllListener} for how to listen for this event.
*
* @event SimpleStore#beforeDestroyAll
* @see SimpleStore~beforeDestroyAllListener
* @see SimpleStore#destroyAll
*/
/**
* Callback signature for the {@link SimpleStore#event:beforeDestroyAll} event.
*
* @example
* function onBeforeDestroyAll (mapperName, query, opts) {
* // do something
* }
* store.on('beforeDestroyAll', onBeforeDestroyAll);
*
* @callback SimpleStore~beforeDestroyAllListener
* @param {string} name The `name` argument received by {@link Mapper#beforeDestroyAll}.
* @param {object} query The `query` argument received by {@link Mapper#beforeDestroyAll}.
* @param {object} opts The `opts` argument received by {@link Mapper#beforeDestroyAll}.
* @see SimpleStore#event:beforeDestroyAll
* @see SimpleStore#destroyAll
* @since 3.0.0
*/
/**
* Fired during {@link SimpleStore#destroyAll}. See
* {@link SimpleStore~afterDestroyAllListener} for how to listen for this event.
*
* @event SimpleStore#afterDestroyAll
* @see SimpleStore~afterDestroyAllListener
* @see SimpleStore#destroyAll
*/
/**
* Callback signature for the {@link SimpleStore#event:afterDestroyAll} event.
*
* @example
* function onAfterDestroyAll (mapperName, query, opts, result) {
* // do something
* }
* store.on('afterDestroyAll', onAfterDestroyAll);
*
* @callback SimpleStore~afterDestroyAllListener
* @param {string} name The `name` argument received by {@link Mapper#afterDestroyAll}.
* @param {object} query The `query` argument received by {@link Mapper#afterDestroyAll}.
* @param {object} opts The `opts` argument received by {@link Mapper#afterDestroyAll}.
* @param {object} result The `result` argument received by {@link Mapper#afterDestroyAll}.
* @see SimpleStore#event:afterDestroyAll
* @see SimpleStore#destroyAll
* @since 3.0.0
*/
/**
* Wrapper for {@link Mapper#destroyAll}. Removes any destroyed records from
* the in-memory store.
*
* @example
* import { SimpleStore } from 'js-data';
* import { HttpAdapter } from 'js-data-http';
*
* const store = new SimpleStore();
* store.registerAdapter('http', new HttpAdapter(), { default: true });
*
* store.defineMapper('book');
*
* store.add('book', { id: 1234, title: 'Data Management is Hard' });
*
* // Since this example uses the http adapter, we'll get something like:
* //
* // DELETE /book/1234
* store.destroy('book', 1234).then(() => {
* // The book record is gone from the in-memory store
* console.log(store.get('book', 1234)); // undefined
* return store.find('book', 1234);
* }).then((book) {
* // The book was deleted from the database too
* console.log(book); // undefined
* });
*
* @fires SimpleStore#beforeDestroyAll
* @fires SimpleStore#afterDestroyAll
* @fires SimpleStore#remove
* @method SimpleStore#destroyAll
* @param {string} name Name of the {@link Mapper} to target.
* @param {object} [query] Passed to {@link Mapper#destroyAll}.
* @param {object} [opts] Passed to {@link Mapper#destroyAll}. See
* {@link Mapper#destroyAll} for more configuration options.
* @returns {Promise} Resolves when the delete completes.
* @since 3.0.0
*/
destroyAll (name, query, opts: any = {}) {
return super.destroyAll(name, query, opts).then(result => {
const records = this.getCollection(name).removeAll(query, opts)
if (opts.raw) {
result.data = records
} else {
result = records
}
const hash = this.hashQuery(name, query, opts)
delete this._pendingQueries[name][hash]
delete this._completedQueries[name][hash]
return result
})
}
eject (name, id, opts) {
console.warn('DEPRECATED: "eject" is deprecated, use "remove" instead')
return this.remove(name, id, opts)
}
ejectAll (name, query, opts) {
console.warn('DEPRECATED: "ejectAll" is deprecated, use "removeAll" instead')
return this.removeAll(name, query, opts)
}
/**
* Fired during {@link SimpleStore#find}. See
* {@link SimpleStore~beforeFindListener} for how to listen for this event.
*
* @event SimpleStore#beforeFind
* @see SimpleStore~beforeFindListener
* @see SimpleStore#find
*/
/**
* Callback signature for the {@link SimpleStore#event:beforeFind} event.