forked from 418sec/js-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMapper.js
2538 lines (2413 loc) · 85.4 KB
/
Mapper.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
import utils from './utils'
import Component from './Component'
import Record from './Record'
import Schema from './Schema'
import { Relation } from './relations'
import {
belongsTo,
belongsToType,
hasMany,
hasManyType,
hasOne,
hasOneType
} from './decorators'
const DOMAIN = 'Mapper'
const applyDefaultsHooks = [
'beforeCreate',
'beforeCreateMany'
]
const validatingHooks = [
'beforeCreate',
'beforeCreateMany',
'beforeUpdate',
'beforeUpdateAll',
'beforeUpdateMany'
]
const makeNotify = function (num) {
return function (...args) {
const opts = args[args.length - num]
const op = opts.op
this.dbg(op, ...args)
if (applyDefaultsHooks.indexOf(op) !== -1 && opts.applyDefaults !== false) {
const schema = this.getSchema()
if (schema && schema.applyDefaults) {
let toProcess = args[0]
if (!utils.isArray(toProcess)) {
toProcess = [toProcess]
}
toProcess.forEach((record) => {
schema.applyDefaults(record)
})
}
}
// Automatic validation
if (validatingHooks.indexOf(op) !== -1 && !opts.noValidate) {
// Save current value of option
const originalExistingOnly = opts.existingOnly
// For updates, ignore required fields if they aren't present
if (op.indexOf('beforeUpdate') === 0 && opts.existingOnly === undefined) {
opts.existingOnly = true
}
const errors = this.validate(args[op === 'beforeUpdate' ? 1 : 0], utils.pick(opts, ['existingOnly']))
// Restore option
opts.existingOnly = originalExistingOnly
// Abort lifecycle due to validation errors
if (errors) {
const err = new Error('validation failed')
err.errors = errors
return utils.reject(err)
}
}
// Emit lifecycle event
if (opts.notify || (opts.notify === undefined && this.notify)) {
setTimeout(() => {
this.emit(op, ...args)
})
}
}
}
// These are the default implementations of all of the lifecycle hooks
const notify = makeNotify(1)
const notify2 = makeNotify(2)
// This object provides meta information used by Mapper#crud to actually
// execute each lifecycle method
const LIFECYCLE_METHODS = {
count: {
defaults: [{}, {}],
skip: true,
types: []
},
destroy: {
defaults: [{}, {}],
skip: true,
types: []
},
destroyAll: {
defaults: [{}, {}],
skip: true,
types: []
},
find: {
defaults: [undefined, {}],
types: []
},
findAll: {
defaults: [{}, {}],
types: []
},
sum: {
defaults: [undefined, {}, {}],
skip: true,
types: []
},
update: {
adapterArgs (mapper, id, props, opts) {
return [id, mapper.toJSON(props, opts), opts]
},
beforeAssign: 1,
defaults: [undefined, {}, {}],
types: []
},
updateAll: {
adapterArgs (mapper, props, query, opts) {
return [mapper.toJSON(props, opts), query, opts]
},
beforeAssign: 0,
defaults: [{}, {}, {}],
types: []
},
updateMany: {
adapterArgs (mapper, records, opts) {
return [records.map((record) => mapper.toJSON(record, opts)), opts]
},
beforeAssign: 0,
defaults: [[], {}],
types: []
}
}
const MAPPER_DEFAULTS = {
/**
* Hash of registered adapters. Don't modify directly. Use
* {@link Mapper#registerAdapter} instead.
*
* @default {}
* @name Mapper#_adapters
* @since 3.0.0
* @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"]
*/
_adapters: {},
/**
* Whether {@link Mapper#beforeCreate} and {@link Mapper#beforeCreateMany}
* should automatically receive default values according to the Mapper's schema.
*
* @default true
* @name Mapper#applyDefaults
* @since 3.0.0
* @type {boolean}
*/
applyDefaults: true,
/**
* Whether to augment {@link Mapper#recordClass} with ES5 getters and setters
* according to the properties defined in {@link Mapper#schema}. This makes
* possible validation and change tracking on individual properties
* when using the dot (e.g. `user.name = "Bob"`) operator to modify a
* property, and is `true` by default.
*
* @default true
* @name Mapper#applySchema
* @since 3.0.0
* @type {boolean}
*/
applySchema: true,
/**
* The name of the registered adapter that this Mapper should used by default.
*
* @default "http"
* @name Mapper#defaultAdapter
* @since 3.0.0
* @tutorial ["http://www.js-data.io/v3.0/docs/connecting-to-a-data-source","Connecting to a data source"]
* @type {string}
*/
defaultAdapter: 'http',
/**
* The field used as the unique identifier on records handled by this Mapper.
*
* @default id
* @name Mapper#idAttribute
* @since 3.0.0
* @type {string}
*/
idAttribute: 'id',
/**
* Whether records created from this mapper keep changeHistory on property changes.
*
* @default true
* @name Mapper#keepChangeHistory
* @since 3.0.0
* @type {boolean}
*/
keepChangeHistory: true,
/**
* Whether this Mapper should emit operational events.
*
* @default true
* @name Mapper#notify
* @since 3.0.0
* @type {boolean}
*/
notify: true,
/**
* Whether to skip validation when the Record instances are created.
*
* @default false
* @name Mapper#noValidate
* @since 3.0.0
* @type {boolean}
*/
noValidate: false,
/**
* Whether {@link Mapper#create}, {@link Mapper#createMany},
* {@link Mapper#update}, {@link Mapper#updateAll}, {@link Mapper#updateMany},
* {@link Mapper#find}, {@link Mapper#findAll}, {@link Mapper#destroy},
* {@link Mapper#destroyAll}, {@link Mapper#count}, and {@link Mapper#sum}
* should return a raw result object that contains both the instance data
* returned by the adapter _and_ metadata about the operation.
*
* The default is to NOT return the result object, and instead return just the
* instance data.
*
* @default false
* @name Mapper#raw
* @since 3.0.0
* @type {boolean}
*/
raw: false,
/**
* Whether records created from this mapper automatically validate their properties
* when their properties are modified.
*
* @default true
* @name Mapper#validateOnSet
* @since 3.0.0
* @type {boolean}
*/
validateOnSet: true
}
/**
* The core of JSData's [ORM/ODM][orm] implementation. Given a minimum amout of
* meta information about a resource, a Mapper can perform generic CRUD
* operations against that resource. Apart from its configuration, a Mapper is
* stateless. The particulars of various persistence layers have been abstracted
* into adapters, which a Mapper uses to perform its operations.
*
* The term "Mapper" comes from the [Data Mapper Pattern][pattern] described in
* Martin Fowler's [Patterns of Enterprise Application Architecture][book]. A
* Data Mapper moves data between [in-memory object instances][record] and a
* relational or document-based database. JSData's Mapper can work with any
* persistence layer you can write an adapter for.
*
* _("Model" is a heavily overloaded term and is avoided in this documentation
* to prevent confusion.)_
*
* [orm]: https://en.wikipedia.org/wiki/Object-relational_mapping
*
* @example
* [pattern]: https://en.wikipedia.org/wiki/Data_mapper_pattern
* [book]: http://martinfowler.com/books/eaa.html
* [record]: Record.html
* // Import and instantiate
* import { Mapper } from 'js-data';
* const UserMapper = new Mapper({ name: 'user' });
*
* @example
* // Define a Mapper using the Container component
* import { Container } from 'js-data';
* const store = new Container();
* store.defineMapper('user');
*
* @class Mapper
* @extends Component
* @param {object} opts Configuration options.
* @param {boolean} [opts.applySchema=true] See {@link Mapper#applySchema}.
* @param {boolean} [opts.debug=false] See {@link Component#debug}.
* @param {string} [opts.defaultAdapter=http] See {@link Mapper#defaultAdapter}.
* @param {string} [opts.idAttribute=id] See {@link Mapper#idAttribute}.
* @param {object} [opts.methods] See {@link Mapper#methods}.
* @param {string} opts.name See {@link Mapper#name}.
* @param {boolean} [opts.notify] See {@link Mapper#notify}.
* @param {boolean} [opts.raw=false] See {@link Mapper#raw}.
* @param {Function|boolean} [opts.recordClass] See {@link Mapper#recordClass}.
* @param {Object|Schema} [opts.schema] See {@link Mapper#schema}.
* @returns {Mapper} A new {@link Mapper} instance.
* @see http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper
* @since 3.0.0
* @tutorial ["http://www.js-data.io/v3.0/docs/components-of-jsdata#mapper","Components of JSData: Mapper"]
* @tutorial ["http://www.js-data.io/v3.0/docs/modeling-your-data","Modeling your data"]
*/
function Mapper (opts) {
utils.classCallCheck(this, Mapper)
Component.call(this)
opts || (opts = {})
// Prepare certain properties to be non-enumerable
Object.defineProperties(this, {
_adapters: {
value: undefined,
writable: true
},
/**
* The {@link Container} that holds this Mapper. __Do not modify.__
*
* @name Mapper#lifecycleMethods
* @since 3.0.0
* @type {Object}
*/
datastore: {
value: undefined,
writable: true
},
/**
* The meta information describing this Mapper's available lifecycle
* methods. __Do not modify.__
*
* @name Mapper#lifecycleMethods
* @since 3.0.0
* @type {Object}
*/
lifecycleMethods: {
value: LIFECYCLE_METHODS
},
/**
* Set to `false` to force the Mapper to work with POJO objects only.
*
* @example
* // Use POJOs only.
* import { Mapper, Record } from 'js-data';
* const UserMapper = new Mapper({ recordClass: false });
* UserMapper.recordClass // false;
* const user = UserMapper.createRecord();
* user instanceof Record; // false
*
* @example
* // Set to a custom class to have records wrapped in your custom class.
* import { Mapper, Record } from 'js-data';
* // Custom class
* class User {
* constructor (props = {}) {
* for (var key in props) {
* if (props.hasOwnProperty(key)) {
* this[key] = props[key];
* }
* }
* }
* }
* const UserMapper = new Mapper({ recordClass: User });
* UserMapper.recordClass; // function User() {}
* const user = UserMapper.createRecord();
* user instanceof Record; // false
* user instanceof User; // true
*
*
* @example
* // Extend the {@link Record} class.
* import { Mapper, Record } from 'js-data';
* // Custom class
* class User extends Record {
* constructor () {
* super(props);
* }
* }
* const UserMapper = new Mapper({ recordClass: User });
* UserMapper.recordClass; // function User() {}
* const user = UserMapper.createRecord();
* user instanceof Record; // true
* user instanceof User; // true
*
* @name Mapper#recordClass
* @default {@link Record}
* @see Record
* @since 3.0.0
*/
recordClass: {
value: undefined,
writable: true
},
/**
* This Mapper's {@link Schema}.
*
* @example <caption>Mapper#schema</caption>
* const JSData = require('js-data');
* const { Mapper } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const UserMapper = new Mapper({
* name: 'user',
* schema: {
* properties: {
* id: { type: 'number' },
* first: { type: 'string', track: true },
* last: { type: 'string', track: true },
* role: { type: 'string', track: true, required: true },
* age: { type: 'integer', track: true },
* is_active: { type: 'number' }
* }
* }
* });
* const user = UserMapper.createRecord({
* id: 1,
* name: 'John',
* role: 'admin'
* });
* user.on('change', function (user, changes) {
* console.log(changes);
* });
* user.on('change:role', function (user, value) {
* console.log('change:role - ' + value);
* });
* user.role = 'owner';
*
* @name Mapper#schema
* @see Schema
* @since 3.0.0
* @type {Schema}
*/
schema: {
value: undefined,
writable: true
}
})
// Apply user-provided configuration
utils.fillIn(this, opts)
// Fill in any missing options with the defaults
utils.fillIn(this, utils.copy(MAPPER_DEFAULTS))
/**
* The name for this Mapper. This is the minimum amount of meta information
* required for a Mapper to be able to execute CRUD operations for a
* Resource.
*
* @name Mapper#name
* @since 3.0.0
* @type {string}
*/
if (!this.name) {
throw utils.err(`new ${DOMAIN}`, 'opts.name')(400, 'string', this.name)
}
// Setup schema, with an empty default schema if necessary
if (this.schema) {
this.schema.type || (this.schema.type = 'object')
if (!(this.schema instanceof Schema)) {
this.schema = new Schema(this.schema || { type: 'object' })
}
}
// Create a subclass of Record that's tied to this Mapper
if (this.recordClass === undefined) {
const superClass = Record
this.recordClass = superClass.extend({
constructor: (function Record () {
var subClass = function Record (props, opts) {
utils.classCallCheck(this, subClass)
superClass.call(this, props, opts)
}
return subClass
})()
})
}
if (this.recordClass) {
this.recordClass.mapper = this
/**
* Functions that should be added to the prototype of {@link Mapper#recordClass}.
*
* @name Mapper#methods
* @since 3.0.0
* @type {Object}
*/
if (utils.isObject(this.methods)) {
utils.addHiddenPropsToTarget(this.recordClass.prototype, this.methods)
}
// We can only apply the schema to the prototype of this.recordClass if the
// class extends Record
if (Record.prototype.isPrototypeOf(Object.create(this.recordClass.prototype)) && this.schema && this.schema.apply && this.applySchema) {
this.schema.apply(this.recordClass.prototype)
}
}
}
export default Component.extend({
constructor: Mapper,
/**
* Mapper lifecycle hook called by {@link Mapper#count}. If this method
* returns a promise then {@link Mapper#count} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterCount
* @param {object} query The `query` argument passed to {@link Mapper#count}.
* @param {object} opts The `opts` argument passed to {@link Mapper#count}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterCount: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#create}. If this method
* returns a promise then {@link Mapper#create} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterCreate
* @param {object} props The `props` argument passed to {@link Mapper#create}.
* @param {object} opts The `opts` argument passed to {@link Mapper#create}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterCreate: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#createMany}. If this method
* returns a promise then {@link Mapper#createMany} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterCreateMany
* @param {array} records The `records` argument passed to {@link Mapper#createMany}.
* @param {object} opts The `opts` argument passed to {@link Mapper#createMany}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterCreateMany: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#destroy}. If this method
* returns a promise then {@link Mapper#destroy} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterDestroy
* @param {(string|number)} id The `id` argument passed to {@link Mapper#destroy}.
* @param {object} opts The `opts` argument passed to {@link Mapper#destroy}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterDestroy: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#destroyAll}. If this method
* returns a promise then {@link Mapper#destroyAll} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterDestroyAll
* @param {*} data The `data` returned by the adapter.
* @param {query} query The `query` argument passed to {@link Mapper#destroyAll}.
* @param {object} opts The `opts` argument passed to {@link Mapper#destroyAll}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterDestroyAll: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#find}. If this method
* returns a promise then {@link Mapper#find} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterFind
* @param {(string|number)} id The `id` argument passed to {@link Mapper#find}.
* @param {object} opts The `opts` argument passed to {@link Mapper#find}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterFind: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#findAll}. If this method
* returns a promise then {@link Mapper#findAll} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterFindAll
* @param {object} query The `query` argument passed to {@link Mapper#findAll}.
* @param {object} opts The `opts` argument passed to {@link Mapper#findAll}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterFindAll: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#sum}. If this method
* returns a promise then {@link Mapper#sum} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterSum
* @param {object} query The `query` argument passed to {@link Mapper#sum}.
* @param {object} opts The `opts` argument passed to {@link Mapper#sum}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterSum: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#update}. If this method
* returns a promise then {@link Mapper#update} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterUpdate
* @param {(string|number)} id The `id` argument passed to {@link Mapper#update}.
* @param {props} props The `props` argument passed to {@link Mapper#update}.
* @param {object} opts The `opts` argument passed to {@link Mapper#update}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterUpdate: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#updateAll}. If this method
* returns a promise then {@link Mapper#updateAll} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterUpdateAll
* @param {object} props The `props` argument passed to {@link Mapper#updateAll}.
* @param {object} query The `query` argument passed to {@link Mapper#updateAll}.
* @param {object} opts The `opts` argument passed to {@link Mapper#updateAll}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterUpdateAll: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#updateMany}. If this method
* returns a promise then {@link Mapper#updateMany} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#afterUpdateMany
* @param {array} records The `records` argument passed to {@link Mapper#updateMany}.
* @param {object} opts The `opts` argument passed to {@link Mapper#updateMany}.
* @param {*} result The result, if any.
* @since 3.0.0
*/
afterUpdateMany: notify2,
/**
* Mapper lifecycle hook called by {@link Mapper#create}. If this method
* returns a promise then {@link Mapper#create} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeCreate
* @param {object} props The `props` argument passed to {@link Mapper#create}.
* @param {object} opts The `opts` argument passed to {@link Mapper#create}.
* @since 3.0.0
*/
beforeCreate: notify,
/**
* Mapper lifecycle hook called by {@link Mapper#createMany}. If this method
* returns a promise then {@link Mapper#createMany} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeCreateMany
* @param {array} records The `records` argument passed to {@link Mapper#createMany}.
* @param {object} opts The `opts` argument passed to {@link Mapper#createMany}.
* @since 3.0.0
*/
beforeCreateMany: notify,
/**
* Mapper lifecycle hook called by {@link Mapper#count}. If this method
* returns a promise then {@link Mapper#count} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeCount
* @param {object} query The `query` argument passed to {@link Mapper#count}.
* @param {object} opts The `opts` argument passed to {@link Mapper#count}.
* @since 3.0.0
*/
beforeCount: notify,
/**
* Mapper lifecycle hook called by {@link Mapper#destroy}. If this method
* returns a promise then {@link Mapper#destroy} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeDestroy
* @param {(string|number)} id The `id` argument passed to {@link Mapper#destroy}.
* @param {object} opts The `opts` argument passed to {@link Mapper#destroy}.
* @since 3.0.0
*/
beforeDestroy: notify,
/**
* Mapper lifecycle hook called by {@link Mapper#destroyAll}. If this method
* returns a promise then {@link Mapper#destroyAll} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeDestroyAll
* @param {query} query The `query` argument passed to {@link Mapper#destroyAll}.
* @param {object} opts The `opts` argument passed to {@link Mapper#destroyAll}.
* @since 3.0.0
*/
beforeDestroyAll: notify,
/**
* Mappers lifecycle hook called by {@link Mapper#find}. If this method
* returns a promise then {@link Mapper#find} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeFind
* @param {(string|number)} id The `id` argument passed to {@link Mapper#find}.
* @param {object} opts The `opts` argument passed to {@link Mapper#find}.
* @since 3.0.0
*/
beforeFind: notify,
/**
* Mapper lifecycle hook called by {@link Mapper#findAll}. If this method
* returns a promise then {@link Mapper#findAll} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeFindAll
* @param {object} query The `query` argument passed to {@link Mapper#findAll}.
* @param {object} opts The `opts` argument passed to {@link Mapper#findAll}.
* @since 3.0.0
*/
beforeFindAll: notify,
/**
* Mapper lifecycle hook called by {@link Mapper#sum}. If this method
* returns a promise then {@link Mapper#sum} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeSum
* @param {string} field The `field` argument passed to {@link Mapper#sum}.
* @param {object} query The `query` argument passed to {@link Mapper#sum}.
* @param {object} opts The `opts` argument passed to {@link Mapper#sum}.
* @since 3.0.0
*/
beforeSum: notify,
/**
* Mapper lifecycle hook called by {@link Mapper#update}. If this method
* returns a promise then {@link Mapper#update} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeUpdate
* @param {(string|number)} id The `id` argument passed to {@link Mapper#update}.
* @param {props} props The `props` argument passed to {@link Mapper#update}.
* @param {object} opts The `opts` argument passed to {@link Mapper#update}.
* @since 3.0.0
*/
beforeUpdate: notify,
/**
* Mapper lifecycle hook called by {@link Mapper#updateAll}. If this method
* returns a promise then {@link Mapper#updateAll} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeUpdateAll
* @param {object} props The `props` argument passed to {@link Mapper#updateAll}.
* @param {object} query The `query` argument passed to {@link Mapper#updateAll}.
* @param {object} opts The `opts` argument passed to {@link Mapper#updateAll}.
* @since 3.0.0
*/
beforeUpdateAll: notify,
/**
* Mapper lifecycle hook called by {@link Mapper#updateMany}. If this method
* returns a promise then {@link Mapper#updateMany} will wait for the promise
* to resolve before continuing.
*
* @method Mapper#beforeUpdateMany
* @param {array} records The `records` argument passed to {@link Mapper#updateMany}.
* @param {object} opts The `opts` argument passed to {@link Mapper#updateMany}.
* @since 3.0.0
*/
beforeUpdateMany: notify,
/**
* This method is called at the end of most lifecycle methods. It does the
* following:
*
* 1. If `opts.raw` is `true`, add this Mapper's configuration to the `opts`
* argument as metadata for the operation.
* 2. Wrap the result data appropriately using {@link Mapper#wrap}, which
* calls {@link Mapper#createRecord}.
*
* @method Mapper#_end
* @private
* @since 3.0.0
*/
_end (result, opts, skip) {
if (opts.raw) {
utils._(result, opts)
}
if (skip) {
return result
}
let _data = opts.raw ? result.data : result
if (_data && utils.isFunction(this.wrap)) {
_data = this.wrap(_data, opts)
if (opts.raw) {
result.data = _data
} else {
result = _data
}
}
return result
},
/**
* Define a belongsTo relationship. Only useful if you're managing your
* Mappers manually and not using a Container or DataStore component.
*
* @example
* PostMapper.belongsTo(UserMapper, {
* // post.user_id points to user.id
* foreignKey: 'user_id'
* // user records will be attached to post records at "post.user"
* localField: 'user'
* });
*
* CommentMapper.belongsTo(UserMapper, {
* // comment.user_id points to user.id
* foreignKey: 'user_id'
* // user records will be attached to comment records at "comment.user"
* localField: 'user'
* });
* CommentMapper.belongsTo(PostMapper, {
* // comment.post_id points to post.id
* foreignKey: 'post_id'
* // post records will be attached to comment records at "comment.post"
* localField: 'post'
* });
*
* @method Mapper#belongsTo
* @see http://www.js-data.io/v3.0/docs/relations
* @since 3.0.0
*/
belongsTo (relatedMapper, opts) {
return belongsTo(relatedMapper, opts)(this)
},
/**
* Select records according to the `query` argument and return the count.
*
* {@link Mapper#beforeCount} will be called before calling the adapter.
* {@link Mapper#afterCount} will be called after calling the adapter.
*
* @example
* // Get the number of published blog posts
* PostMapper.count({ status: 'published' }).then((numPublished) => {
* console.log(numPublished); // e.g. 45
* });
*
* @method Mapper#count
* @param {object} [query={}] Selection query. See {@link query}.
* @param {object} [query.where] See {@link query.where}.
* @param {number} [query.offset] See {@link query.offset}.
* @param {number} [query.limit] See {@link query.limit}.
* @param {string|Array[]} [query.orderBy] See {@link query.orderBy}.
* @param {object} [opts] Configuration options. Refer to the `count` method
* of whatever adapter you're using for more configuration options.
* @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the
* adapter to use.
* @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.
* @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.
* @returns {Promise} Resolves with the count of the selected records.
* @since 3.0.0
*/
count (query, opts) {
return this.crud('count', query, opts)
},
/**
* Fired during {@link Mapper#create}. See
* {@link Mapper~beforeCreateListener} for how to listen for this event.
*
* @event Mapper#beforeCreate
* @see Mapper~beforeCreateListener
* @see Mapper#create
*/
/**
* Callback signature for the {@link Mapper#event:beforeCreate} event.
*
* @example
* function onBeforeCreate (props, opts) {
* // do something
* }
* store.on('beforeCreate', onBeforeCreate);
*
* @callback Mapper~beforeCreateListener
* @param {object} props The `props` argument passed to {@link Mapper#beforeCreate}.
* @param {object} opts The `opts` argument passed to {@link Mapper#beforeCreate}.
* @see Mapper#event:beforeCreate
* @see Mapper#create
* @since 3.0.0
*/
/**
* Fired during {@link Mapper#create}. See
* {@link Mapper~afterCreateListener} for how to listen for this event.
*
* @event Mapper#afterCreate
* @see Mapper~afterCreateListener
* @see Mapper#create
*/
/**
* Callback signature for the {@link Mapper#event:afterCreate} event.
*
* @example
* function onAfterCreate (props, opts, result) {
* // do something
* }
* store.on('afterCreate', onAfterCreate);
*
* @callback Mapper~afterCreateListener
* @param {object} props The `props` argument passed to {@link Mapper#afterCreate}.
* @param {object} opts The `opts` argument passed to {@link Mapper#afterCreate}.
* @param {object} result The `result` argument passed to {@link Mapper#afterCreate}.
* @see Mapper#event:afterCreate
* @see Mapper#create
* @since 3.0.0
*/
/**
* Create and save a new the record using the provided `props`.
*
* {@link Mapper#beforeCreate} will be called before calling the adapter.
* {@link Mapper#afterCreate} will be called after calling the adapter.
*
* @example
* // Create and save a new blog post
* PostMapper.create({
* title: 'Modeling your data',
* status: 'draft'
* }).then((post) => {
* console.log(post); // { id: 1234, status: 'draft', ... }
* });
*
* @fires Mapper#beforeCreate
* @fires Mapper#afterCreate
* @method Mapper#create
* @param {object} props The properties for the new record.
* @param {object} [opts] Configuration options. Refer to the `create` method
* of whatever adapter you're using for more configuration options.
* @param {boolean} [opts.adapter={@link Mapper#defaultAdapter}] Name of the
* adapter to use.
* @param {boolean} [opts.noValidate={@link Mapper#noValidate}] See {@link Mapper#noValidate}.
* @param {boolean} [opts.notify={@link Mapper#notify}] See {@link Mapper#notify}.
* @param {boolean} [opts.raw={@link Mapper#raw}] See {@link Mapper#raw}.
* @param {string[]} [opts.with=[]] Relations to create in a cascading
* create if `props` contains nested relations. NOT performed in a
* transaction. Each nested create will result in another {@link Mapper#create}
* or {@link Mapper#createMany} call.
* @param {string[]} [opts.pass=[]] Relations to send to the adapter as part
* of the payload. Normally relations are not sent.
* @returns {Promise} Resolves with the created record.
* @since 3.0.0
*/
create (props, opts) {
// Default values for arguments
props || (props = {})
opts || (opts = {})
const originalRecord = props
let parentRelationMap = {}
let adapterResponse = {}
// Fill in "opts" with the Mapper's configuration
utils._(opts, this)
opts.adapter = this.getAdapterName(opts)
opts.op = 'beforeCreate'
return this._runHook(opts.op, props, opts).then((props) => {
opts.with || (opts.with = [])
return this._createParentRecordIfRequired(props, opts)
}).then((relationMap) => {
parentRelationMap = relationMap
}).then(() => {
opts.op = 'create'
return this._invokeAdapterMethod(opts.op, props, opts)
}).then((result) => {
adapterResponse = result
}).then(() => {
const createdProps = opts.raw ? adapterResponse.data : adapterResponse
return this._createOrAssignChildRecordIfRequired(createdProps, {
opts,
parentRelationMap,
originalProps: props
})