/
index.js
1147 lines (1052 loc) · 36.2 KB
/
index.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 'js-data'
import {
Adapter,
reserved
} from 'js-data-adapter'
import rethinkdbdash from 'rethinkdbdash'
import snakeCase from 'lodash.snakecase'
const __super__ = Adapter.prototype
const R_OPTS_DEFAULTS = {
db: 'test'
}
const INSERT_OPTS_DEFAULTS = {}
const UPDATE_OPTS_DEFAULTS = {}
const DELETE_OPTS_DEFAULTS = {}
const RUN_OPTS_DEFAULTS = {}
const equal = function (r, row, field, value) {
return row(field).default(null).eq(value)
}
const notEqual = function (r, row, field, value) {
return row(field).default(null).ne(value)
}
/**
* Default predicate functions for the filtering operators.
*
* @name module:js-data-rethinkdb.OPERATORS
* @property {function} = Equality operator.
* @property {function} == Equality operator.
* @property {function} != Inequality operator.
* @property {function} > "Greater than" operator.
* @property {function} >= "Greater than or equal to" operator.
* @property {function} < "Less than" operator.
* @property {function} <= "Less than or equal to" operator.
* @property {function} isectEmpty Operator to test that the intersection
* between two arrays is empty.
* @property {function} isectNotEmpty Operator to test that the intersection
* between two arrays is NOT empty.
* @property {function} in Operator to test whether a value is found in the
* provided array.
* @property {function} notIn Operator to test whether a value is NOT found in
* the provided array.
* @property {function} contains Operator to test whether an array contains the
* provided value.
* @property {function} notContains Operator to test whether an array does NOT
* contain the provided value.
*/
export const OPERATORS = {
'=': equal,
'==': equal,
'===': equal,
'!=': notEqual,
'!==': notEqual,
'>': function (r, row, field, value) {
return row(field).default(null).gt(value)
},
'>=': function (r, row, field, value) {
return row(field).default(null).ge(value)
},
'<': function (r, row, field, value) {
return row(field).default(null).lt(value)
},
'<=': function (r, row, field, value) {
return row(field).default(null).le(value)
},
'isectEmpty': function (r, row, field, value) {
return row(field).default([]).setIntersection(r.expr(value).default([])).count().eq(0)
},
'isectNotEmpty': function (r, row, field, value) {
return row(field).default([]).setIntersection(r.expr(value).default([])).count().ne(0)
},
'in': function (r, row, field, value) {
return r.expr(value).default(r.expr([])).contains(row(field).default(null))
},
'notIn': function (r, row, field, value) {
return r.expr(value).default(r.expr([])).contains(row(field).default(null)).not()
},
'contains': function (r, row, field, value) {
return row(field).default([]).contains(value)
},
'notContains': function (r, row, field, value) {
return row(field).default([]).contains(value).not()
}
}
Object.freeze(OPERATORS)
/**
* RethinkDBAdapter class.
*
* @example
* // Use Container instead of DataStore on the server
* import { Container } from 'js-data';
* import { RethinkDBAdapter } from 'js-data-rethinkdb';
*
* // Create a store to hold your Mappers
* const store = new Container();
*
* // Create an instance of RethinkDBAdapter with default settings
* const adapter = new RethinkDBAdapter();
*
* // Mappers in "store" will use the RethinkDB adapter by default
* store.registerAdapter('rethinkdb', adapter, { default: true });
*
* // Create a Mapper that maps to a "user" table
* store.defineMapper('user');
*
* @class RethinkDBAdapter
* @extends Adapter
* @param {object} [opts] Configuration options.
* @param {boolean} [opts.debug=false] See {@link Adapter#debug}.
* @param {object} [opts.deleteOpts={}] See {@link RethinkDBAdapter#deleteOpts}.
* @param {object} [opts.insertOpts={}] See {@link RethinkDBAdapter#insertOpts}.
* @param {object} [opts.operators={@link module:js-data-rethinkdb.OPERATORS}] See {@link RethinkDBAdapter#operators}.
* @param {object} [opts.r] See {@link RethinkDBAdapter#r}.
* @param {boolean} [opts.raw=false] See {@link Adapter#raw}.
* @param {object} [opts.rOpts={}] See {@link RethinkDBAdapter#rOpts}.
* @param {object} [opts.runOpts={}] See {@link RethinkDBAdapter#runOpts}.
* @param {object} [opts.updateOpts={}] See {@link RethinkDBAdapter#updateOpts}.
*/
export function RethinkDBAdapter (opts) {
utils.classCallCheck(this, RethinkDBAdapter)
opts || (opts = {})
// Setup non-enumerable properties
Object.defineProperties(this, {
/**
* The rethinkdbdash instance used by this adapter. Use this directly when
* you need to write custom queries.
*
* @example <caption>Use default instance.</caption>
* import { RethinkDBAdapter } from 'js-data-rethinkdb';
* const adapter = new RethinkDBAdapter();
* adapter.r.dbDrop('foo').then(...);
*
* @example <caption>Configure default instance.</caption>
* import { RethinkDBAdapter } from 'js-data-rethinkdb';
* const adapter = new RethinkDBAdapter({
* rOpts: {
* user: 'myUser',
* password: 'myPassword'
* }
* });
* adapter.r.dbDrop('foo').then(...);
*
* @example <caption>Provide a custom instance.</caption>
* import rethinkdbdash from 'rethinkdbdash';
* import { RethinkDBAdapter } from 'js-data-rethinkdb';
* const r = rethinkdbdash();
* const adapter = new RethinkDBAdapter({
* r: r
* });
* adapter.r.dbDrop('foo').then(...);
*
* @name RethinkDBAdapter#r
* @type {object}
*/
r: {
writable: true,
value: undefined
},
databases: {
value: {}
},
indices: {
value: {}
},
tables: {
value: {}
}
})
Adapter.call(this, opts)
/**
* Default options to pass to r#insert.
*
* @name RethinkDBAdapter#insertOpts
* @type {object}
* @default {}
*/
this.insertOpts || (this.insertOpts = {})
utils.fillIn(this.insertOpts, INSERT_OPTS_DEFAULTS)
/**
* Default options to pass to r#update.
*
* @name RethinkDBAdapter#updateOpts
* @type {object}
* @default {}
*/
this.updateOpts || (this.updateOpts = {})
utils.fillIn(this.updateOpts, UPDATE_OPTS_DEFAULTS)
/**
* Default options to pass to r#delete.
*
* @name RethinkDBAdapter#deleteOpts
* @type {object}
* @default {}
*/
this.deleteOpts || (this.deleteOpts = {})
utils.fillIn(this.deleteOpts, DELETE_OPTS_DEFAULTS)
/**
* Default options to pass to r#run.
*
* @name RethinkDBAdapter#runOpts
* @type {object}
* @default {}
*/
this.runOpts || (this.runOpts = {})
utils.fillIn(this.runOpts, RUN_OPTS_DEFAULTS)
/**
* Override the default predicate functions for the specified operators.
*
* @name RethinkDBAdapter#operators
* @type {object}
* @default {}
*/
this.operators || (this.operators = {})
utils.fillIn(this.operators, OPERATORS)
/**
* Options to pass to a new `rethinkdbdash` instance, if one was not provided
* at {@link RethinkDBAdapter#r}. See the [rethinkdbdash README][readme] for
* instance options.
*
* [readme]: https://github.com/neumino/rethinkdbdash#importing-the-driver
*
* @example <caption>Connect to localhost:8080, and let the driver find other instances.</caption>
* import { RethinkDBAdapter } from 'js-data-rethinkdb';
* const adapter = new RethinkDBAdapter({
* rOpts: {
* discovery: true
* }
* });
*
* @example <caption>Connect to and only to localhost:8080.</caption>
* import { RethinkDBAdapter } from 'js-data-rethinkdb';
* const adapter = new RethinkDBAdapter();
*
* @example <caption>Do not create a connection pool.</caption>
* import { RethinkDBAdapter } from 'js-data-rethinkdb';
* const adapter = new RethinkDBAdapter({
* rOpts: {
* pool: false
* }
* });
*
* @example <caption>Connect to a cluster seeding from `192.168.0.100`, `192.168.0.101`, `192.168.0.102`.</caption>
* import { RethinkDBAdapter } from 'js-data-rethinkdb';
* const adapter = new RethinkDBAdapter({
* rOpts: {
* servers: [
* { host: '192.168.0.100', port: 28015 },
* { host: '192.168.0.101', port: 28015 },
* { host: '192.168.0.102', port: 28015 }
* ]
* }
* });
*
* @name RethinkDBAdapter#rOpts
* @see https://github.com/neumino/rethinkdbdash#importing-the-driver
* @type {object}
*/
this.rOpts || (this.rOpts = {})
utils.fillIn(this.rOpts, R_OPTS_DEFAULTS)
this.r || (this.r = rethinkdbdash(this.rOpts))
}
Adapter.extend({
constructor: RethinkDBAdapter,
_handleErrors (cursor) {
if (cursor && cursor.errors > 0) {
if (cursor.first_error) {
throw new Error(cursor.first_error)
}
throw new Error('Unknown RethinkDB Error')
}
},
_count (mapper, query, opts) {
opts || (opts = {})
query || (query = {})
return this.filterSequence(this.selectTable(mapper, opts), query)
.count()
.run(this.getOpt('runOpts', opts))
.then((count) => [count, {}])
},
_create (mapper, props, opts) {
props || (props = {})
opts || (opts = {})
const insertOpts = this.getOpt('insertOpts', opts)
insertOpts.returnChanges = true
return this.selectTable(mapper, opts)
.insert(props, insertOpts)
.run(this.getOpt('runOpts', opts))
.then((cursor) => {
this._handleErrors(cursor)
let record
if (cursor && cursor.changes && cursor.changes.length && cursor.changes[0].new_val) {
record = cursor.changes[0].new_val
}
return [record, cursor]
})
},
_createMany (mapper, props, opts) {
props || (props = {})
opts || (opts = {})
const insertOpts = this.getOpt('insertOpts', opts)
insertOpts.returnChanges = true
return this.selectTable(mapper, opts)
.insert(props, insertOpts)
.run(this.getOpt('runOpts', opts))
.then((cursor) => {
this._handleErrors(cursor)
let records = []
if (cursor && cursor.changes && cursor.changes.length && cursor.changes) {
records = cursor.changes.map((change) => change.new_val)
}
return [records, cursor]
})
},
_destroy (mapper, id, opts) {
opts || (opts = {})
return this.selectTable(mapper, opts)
.get(id)
.delete(this.getOpt('deleteOpts', opts))
.run(this.getOpt('runOpts', opts))
.then((cursor) => {
this._handleErrors(cursor)
return [undefined, cursor]
})
},
_destroyAll (mapper, query, opts) {
query || (query = {})
opts || (opts = {})
return this.filterSequence(this.selectTable(mapper, opts), query)
.delete(this.getOpt('deleteOpts', opts))
.run(this.getOpt('runOpts', opts))
.then((cursor) => {
this._handleErrors(cursor)
return [undefined, cursor]
})
},
_find (mapper, id, opts) {
opts || (opts = {})
return this._pluck(mapper, this.selectTable(mapper, opts).get(id), opts)
.run(this.getOpt('runOpts', opts))
.then((record) => {
if (!record) {
record = undefined
}
return [record, {}]
})
},
_findAll (mapper, query, opts) {
opts || (opts = {})
query || (query = {})
return this._pluck(mapper, this.filterSequence(this.selectTable(mapper, opts), query), opts)
.run(this.getOpt('runOpts', opts))
.then((records) => [records, {}])
},
_pluck (mapper, rql, opts) {
if (utils.isString(opts.fields)) {
opts.fields = [opts.fields]
}
if (utils.isArray(opts.fields)) {
return rql.pluck(...opts.fields)
}
return rql
},
_sum (mapper, field, query, opts) {
if (!utils.isString(field)) {
throw new Error('field must be a string!')
}
opts || (opts = {})
query || (query = {})
return this.filterSequence(this.selectTable(mapper, opts), query)
.sum(field)
.run(this.getOpt('runOpts', opts))
.then((sum) => [sum, {}])
},
_update (mapper, id, props, opts) {
props || (props = {})
opts || (opts = {})
const updateOpts = this.getOpt('updateOpts', opts)
updateOpts.returnChanges = true
return this.selectTable(mapper, opts)
.get(id)
.update(props, updateOpts)
.run(this.getOpt('runOpts', opts))
.then((cursor) => {
this._handleErrors(cursor)
if (cursor.skipped) {
throw new Error('Not Found')
} else if (cursor && cursor.changes && cursor.changes.length && cursor.changes[0].new_val) {
return [cursor.changes[0].new_val, cursor]
} else {
return this._find(mapper, id, opts)
}
})
},
_updateAll (mapper, props, query, opts) {
props || (props = {})
query || (query = {})
opts || (opts = {})
const updateOpts = this.getOpt('updateOpts', opts)
updateOpts.returnChanges = true
return this.filterSequence(this.selectTable(mapper, opts), query)
.update(props, updateOpts)
.run(this.getOpt('runOpts', opts))
.then((cursor) => {
let records = []
this._handleErrors(cursor)
if (cursor && cursor.changes && cursor.changes.length) {
records = cursor.changes.map((change) => change.new_val)
}
return [records, cursor]
})
},
_updateMany (mapper, records, opts) {
records || (records = [])
opts || (opts = {})
const insertOpts = this.getOpt('insertOpts', opts)
insertOpts.returnChanges = true
insertOpts.conflict = 'update'
return this.selectTable(mapper, opts)
.insert(records, insertOpts)
.run(this.getOpt('runOpts', opts))
.then((cursor) => {
records = []
this._handleErrors(cursor)
if (cursor && cursor.changes && cursor.changes.length) {
records = cursor.changes.map((change) => change.new_val)
}
return [records, cursor]
})
},
_applyWhereFromObject (where) {
const fields = []
const ops = []
const predicates = []
utils.forOwn(where, (clause, field) => {
if (!utils.isObject(clause)) {
clause = {
'==': clause
}
}
utils.forOwn(clause, (expr, op) => {
fields.push(field)
ops.push(op)
predicates.push(expr)
})
})
return {
fields,
ops,
predicates
}
},
_applyWhereFromArray (where) {
const groups = []
where.forEach((_where, i) => {
if (utils.isString(_where)) {
return
}
const prev = where[i - 1]
const parser = utils.isArray(_where) ? this._applyWhereFromArray : this._applyWhereFromObject
const group = parser.call(this, _where)
if (prev === 'or') {
group.isOr = true
}
groups.push(group)
})
groups.isArray = true
return groups
},
_testObjectGroup (rql, group, row, opts) {
let i
const r = this.r
const fields = group.fields
const ops = group.ops
const predicates = group.predicates
const len = ops.length
for (i = 0; i < len; i++) {
let op = ops[i]
const isOr = op.charAt(0) === '|'
op = isOr ? op.substr(1) : op
const predicateFn = this.getOperator(op, opts)
if (predicateFn) {
const predicateResult = predicateFn(r, row, fields[i], predicates[i])
if (isOr) {
rql = rql ? rql.or(predicateResult) : predicateResult
} else {
rql = rql ? rql.and(predicateResult) : predicateResult
}
} else {
throw new Error(`Operator ${op} not supported!`)
}
}
return rql
},
_testArrayGroup (rql, groups, row, opts) {
let i
const len = groups.length
for (i = 0; i < len; i++) {
const group = groups[i]
let subQuery
if (group.isArray) {
subQuery = this._testArrayGroup(rql, group, row, opts)
} else {
subQuery = this._testObjectGroup(null, group, row, opts)
}
if (groups[i - 1]) {
if (group.isOr) {
rql = rql.or(subQuery)
} else {
rql = rql.and(subQuery)
}
} else {
rql = rql ? rql.and(subQuery) : subQuery
}
}
return rql
},
/**
* Apply the specified selection query to the provided RQL sequence.
*
* @name RethinkDBAdapter#filterSequence
* @method
* @param {object} mapper The mapper.
* @param {object} [query] Selection query.
* @param {object} [query.where] Filtering criteria.
* @param {string|Array} [query.orderBy] Sorting criteria.
* @param {string|Array} [query.sort] Same as `query.sort`.
* @param {number} [query.limit] Limit results.
* @param {number} [query.skip] Offset results.
* @param {number} [query.offset] Same as `query.skip`.
* @param {object} [opts] Configuration options.
* @param {object} [opts.operators] Override the default predicate functions
* for specified operators.
*/
filterSequence (sequence, query, opts) {
const r = this.r
query = utils.plainCopy(query || {})
opts || (opts = {})
opts.operators || (opts.operators = {})
query.where || (query.where = {})
query.orderBy || (query.orderBy = query.sort)
query.orderBy || (query.orderBy = [])
query.skip || (query.skip = query.offset)
// Transform non-keyword properties to "where" clause configuration
utils.forOwn(query, (config, keyword) => {
if (reserved.indexOf(keyword) === -1) {
if (utils.isObject(config)) {
query.where[keyword] = config
} else {
query.where[keyword] = {
'==': config
}
}
delete query[keyword]
}
})
let rql = sequence
// Filter
let groups
if (utils.isObject(query.where) && Object.keys(query.where).length !== 0) {
groups = this._applyWhereFromArray([query.where])
} else if (utils.isArray(query.where)) {
groups = this._applyWhereFromArray(query.where)
}
if (groups) {
rql = rql.filter((row) => this._testArrayGroup(null, groups, row, opts) || true)
}
// Sort
if (query.orderBy) {
if (utils.isString(query.orderBy)) {
query.orderBy = [
[query.orderBy, 'asc']
]
}
for (var i = 0; i < query.orderBy.length; i++) {
if (utils.isString(query.orderBy[i])) {
query.orderBy[i] = [query.orderBy[i], 'asc']
}
rql = (query.orderBy[i][1] || '').toUpperCase() === 'DESC' ? rql.orderBy(r.desc(query.orderBy[i][0])) : rql.orderBy(query.orderBy[i][0])
}
}
// Offset
if (query.skip) {
rql = rql.skip(+query.skip)
}
// Limit
if (query.limit) {
rql = rql.limit(+query.limit)
}
return rql
},
selectDb (opts) {
return this.r.db(utils.isUndefined(opts.db) ? this.rOpts.db : opts.db)
},
selectTable (mapper, opts) {
return this.selectDb(opts).table(mapper.table || snakeCase(mapper.name))
},
waitForDb (opts) {
opts || (opts = {})
const db = utils.isUndefined(opts.db) ? this.rOpts.db : opts.db
if (!this.databases[db]) {
this.databases[db] = this.r.branch(
this.r.dbList().contains(db),
true,
this.r.dbCreate(db)
).run()
}
return this.databases[db]
},
waitForTable (mapper, opts) {
opts || (opts = {})
const table = utils.isString(mapper) ? mapper : (mapper.table || snakeCase(mapper.name))
let db = utils.isUndefined(opts.db) ? this.rOpts.db : opts.db
return this.waitForDb(opts).then(() => {
this.tables[db] = this.tables[db] || {}
if (!this.tables[db][table]) {
this.tables[db][table] = this.r.branch(this.r.db(db).tableList().contains(table), true, this.r.db(db).tableCreate(table)).run()
}
return this.tables[db][table]
})
},
waitForIndex (table, index, opts) {
opts || (opts = {})
let db = utils.isUndefined(opts.db) ? this.rOpts.db : opts.db
return this.waitForDb(opts).then(() => this.waitForTable(table, opts)).then(() => {
this.indices[db] = this.indices[db] || {}
this.indices[db][table] = this.indices[db][table] || {}
if (!this.tables[db][table][index]) {
this.tables[db][table][index] = this.r.branch(this.r.db(db).table(table).indexList().contains(index), true, this.r.db(db).table(table).indexCreate(index)).run().then(() => {
return this.r.db(db).table(table).indexWait(index).run()
})
}
return this.tables[db][table][index]
})
},
/**
* Return the number of records that match the selection query.
*
* @name RethinkDBAdapter#count
* @method
* @param {object} mapper the mapper.
* @param {object} [query] Selection query.
* @param {object} [query.where] Filtering criteria.
* @param {string|Array} [query.orderBy] Sorting criteria.
* @param {string|Array} [query.sort] Same as `query.sort`.
* @param {number} [query.limit] Limit results.
* @param {number} [query.skip] Offset results.
* @param {number} [query.offset] Same as `query.skip`.
* @param {object} [opts] Configuration options.
* @param {object} [opts.operators] Override the default predicate functions
* for specified operators.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {object} [opts.runOpts] Options to pass to r#run.
* @return {Promise}
*/
count (mapper, query, opts) {
opts || (opts = {})
query || (query = {})
return this.waitForTable(mapper, opts)
.then(() => __super__.count.call(this, mapper, query, opts))
},
/**
* Create a new record.
*
* @name RethinkDBAdapter#create
* @method
* @param {object} mapper The mapper.
* @param {object} props The record to be created.
* @param {object} [opts] Configuration options.
* @param {object} [opts.insertOpts] Options to pass to r#insert.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {object} [opts.runOpts] Options to pass to r#run.
* @return {Promise}
*/
create (mapper, props, opts) {
props || (props = {})
opts || (opts = {})
return this.waitForTable(mapper, opts)
.then(() => __super__.create.call(this, mapper, props, opts))
},
/**
* Create multiple records in a single batch.
*
* @name RethinkDBAdapter#createMany
* @method
* @param {object} mapper The mapper.
* @param {object} props The records to be created.
* @param {object} [opts] Configuration options.
* @param {object} [opts.insertOpts] Options to pass to r#insert.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {object} [opts.runOpts] Options to pass to r#run.
* @return {Promise}
*/
createMany (mapper, props, opts) {
props || (props = {})
opts || (opts = {})
return this.waitForTable(mapper, opts)
.then(() => __super__.createMany.call(this, mapper, props, opts))
},
/**
* Destroy the record with the given primary key.
*
* @name RethinkDBAdapter#destroy
* @method
* @param {object} mapper The mapper.
* @param {(string|number)} id Primary key of the record to destroy.
* @param {object} [opts] Configuration options.
* @param {object} [opts.deleteOpts] Options to pass to r#delete.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {object} [opts.runOpts] Options to pass to r#run.
* @return {Promise}
*/
destroy (mapper, id, opts) {
opts || (opts = {})
return this.waitForTable(mapper, opts)
.then(() => __super__.destroy.call(this, mapper, id, opts))
},
/**
* Destroy the records that match the selection query.
*
* @name RethinkDBAdapter#destroyAll
* @method
* @param {object} mapper the mapper.
* @param {object} [query] Selection query.
* @param {object} [query.where] Filtering criteria.
* @param {string|Array} [query.orderBy] Sorting criteria.
* @param {string|Array} [query.sort] Same as `query.sort`.
* @param {number} [query.limit] Limit results.
* @param {number} [query.skip] Offset results.
* @param {number} [query.offset] Same as `query.skip`.
* @param {object} [opts] Configuration options.
* @param {object} [opts.deleteOpts] Options to pass to r#delete.
* @param {object} [opts.operators] Override the default predicate functions
* for specified operators.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {object} [opts.runOpts] Options to pass to r#run.
* @return {Promise}
*/
destroyAll (mapper, query, opts) {
opts || (opts = {})
query || (query = {})
return this.waitForTable(mapper, opts)
.then(() => __super__.destroyAll.call(this, mapper, query, opts))
},
/**
* Retrieve the record with the given primary key.
*
* @name RethinkDBAdapter#find
* @method
* @param {object} mapper The mapper.
* @param {(string|number)} id Primary key of the record to retrieve.
* @param {object} [opts] Configuration options.
* @param {string[]} [opts.fields] Select a subset of fields to be returned.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {object} [opts.runOpts] Options to pass to r#run.
* @param {string[]} [opts.with=[]] Relations to eager load.
* @return {Promise}
*/
find (mapper, id, opts) {
opts || (opts = {})
opts.with || (opts.with = [])
const relationList = mapper.relationList || []
let tasks = [this.waitForTable(mapper, opts)]
relationList.forEach((def) => {
const relationName = def.relation
const relationDef = def.getRelation()
if (!opts.with || opts.with.indexOf(relationName) === -1) {
return
}
if (def.foreignKey && def.type !== 'belongsTo') {
if (def.type === 'belongsTo') {
tasks.push(this.waitForIndex(mapper.table || snakeCase(mapper.name), def.foreignKey, opts))
} else {
tasks.push(this.waitForIndex(relationDef.table || snakeCase(relationDef.name), def.foreignKey, opts))
}
}
})
return Promise.all(tasks).then(() => __super__.find.call(this, mapper, id, opts))
},
/**
* Retrieve the records that match the selection query.
*
* @name RethinkDBAdapter#findAll
* @method
* @param {object} mapper The mapper.
* @param {object} [query] Selection query.
* @param {object} [query.where] Filtering criteria.
* @param {string|Array} [query.orderBy] Sorting criteria.
* @param {string|Array} [query.sort] Same as `query.sort`.
* @param {number} [query.limit] Limit results.
* @param {number} [query.skip] Offset results.
* @param {number} [query.offset] Same as `query.skip`.
* @param {object} [opts] Configuration options.
* @param {string[]} [opts.fields] Select a subset of fields to be returned.
* @param {object} [opts.operators] Override the default predicate functions
* for specified operators.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {object} [opts.runOpts] Options to pass to r#run.
* @param {string[]} [opts.with=[]] Relations to eager load.
* @return {Promise}
*/
findAll (mapper, query, opts) {
opts || (opts = {})
opts.with || (opts.with = [])
query || (query = {})
const relationList = mapper.relationList || []
let tasks = [this.waitForTable(mapper, opts)]
relationList.forEach((def) => {
const relationName = def.relation
const relationDef = def.getRelation()
if (!opts.with || opts.with.indexOf(relationName) === -1) {
return
}
if (def.foreignKey && def.type !== 'belongsTo') {
if (def.type === 'belongsTo') {
tasks.push(this.waitForIndex(mapper.table || snakeCase(mapper.name), def.foreignKey, opts))
} else {
tasks.push(this.waitForIndex(relationDef.table || snakeCase(relationDef.name), def.foreignKey, opts))
}
}
})
return Promise.all(tasks).then(() => __super__.findAll.call(this, mapper, query, opts))
},
/**
* Resolve the predicate function for the specified operator based on the
* given options and this adapter's settings.
*
* @name RethinkDBAdapter#getOperator
* @method
* @param {string} operator The name of the operator.
* @param {object} [opts] Configuration options.
* @param {object} [opts.operators] Override the default predicate functions
* for specified operators.
* @return {*} The predicate function for the specified operator.
*/
getOperator (operator, opts) {
opts || (opts = {})
opts.operators || (opts.operators = {})
let ownOps = this.operators || {}
return utils.isUndefined(opts.operators[operator]) ? ownOps[operator] : opts.operators[operator]
},
/**
* Return the sum of the specified field of records that match the selection
* query.
*
* @name RethinkDBAdapter#sum
* @method
* @param {object} mapper The mapper.
* @param {string} field The field to sum.
* @param {object} [query] Selection query.
* @param {object} [query.where] Filtering criteria.
* @param {string|Array} [query.orderBy] Sorting criteria.
* @param {string|Array} [query.sort] Same as `query.sort`.
* @param {number} [query.limit] Limit results.
* @param {number} [query.skip] Offset results.
* @param {number} [query.offset] Same as `query.skip`.
* @param {object} [opts] Configuration options.
* @param {object} [opts.operators] Override the default predicate functions
* for specified operators.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {object} [opts.runOpts] Options to pass to r#run.
* @return {Promise}
*/
sum (mapper, field, query, opts) {
opts || (opts = {})
query || (query = {})
return this.waitForTable(mapper, opts)
.then(() => __super__.sum.call(this, mapper, field, query, opts))
},
/**
* Apply the given update to the record with the specified primary key.
*
* @name RethinkDBAdapter#update
* @method
* @param {object} mapper The mapper.
* @param {(string|number)} id The primary key of the record to be updated.
* @param {object} props The update to apply to the record.
* @param {object} [opts] Configuration options.
* @param {object} [opts.updateOpts] Options to pass to r#update.
* @param {boolean} [opts.raw=false] Whether to return a more detailed
* response object.
* @param {object} [opts.runOpts] Options to pass to r#run.
* @return {Promise}
*/
update (mapper, id, props, opts) {
props || (props = {})
opts || (opts = {})
return this.waitForTable(mapper, opts)
.then(() => __super__.update.call(this, mapper, id, props, opts))
},
/**
* Apply the given update to all records that match the selection query.
*
* @name RethinkDBAdapter#updateAll
* @method
* @param {object} mapper The mapper.
* @param {object} props The update to apply to the selected records.
* @param {object} [query] Selection query.
* @param {object} [query.where] Filtering criteria.
* @param {string|Array} [query.orderBy] Sorting criteria.
* @param {string|Array} [query.sort] Same as `query.sort`.
* @param {number} [query.limit] Limit results.
* @param {number} [query.skip] Offset results.
* @param {number} [query.offset] Same as `query.skip`.
* @param {object} [opts] Configuration options.
* @param {object} [opts.operators] Override the default predicate functions
* for specified operators.