-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
854 lines (807 loc) · 42.6 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
const _ = require('@sailshq/lodash');
const AWS = require('aws-sdk');
const util = require('./utils/app.util');
let dynamoDb;
let client;
/**
* Module state
*/
// Private var to track of all the datastores that use this adapter. In order for your adapter
// to be able to connect to the database, you'll want to expose this var publicly as well.
// (See the `registerDatastore()` method for info on the format of each datastore entry herein.)
//
// > Note that this approach of process global state will be changing in an upcoming version of
// > the Waterline adapter spec (a breaking change). But if you follow the conventions laid out
// > below in this adapter template, future upgrades should be a breeze.
var registeredDatastores = {};
/**
* sails-dynamodb-v1
*
* Expose the adapater definition.
*
* > Most of the methods below are optional.
* >
* > If you don't need / can't get to every method, just implement
* > what you have time for. The other methods will only fail if
* > you try to call them!
* >
* > For many adapters, this file is all you need. For very complex adapters, you may need more flexiblity.
* > In any case, it's probably a good idea to start with one file and refactor only if necessary.
* > If you do go that route, it's conventional in Node to create a `./lib` directory for your private submodules
* > and `require` them at the top of this file with other dependencies. e.g.:
* > ```
* > var updateMethod = require('./lib/update');
* > ```
*
* @type {Dictionary}
*/
module.exports = {
// The identity of this adapter, to be referenced by datastore configurations in a Sails app.
identity: 'sails-dynamodb-v1',
// Waterline Adapter API Version
//
// > Note that this is not necessarily tied to the major version release cycle of Sails/Waterline!
// > For example, Sails v1.5.0 might generate apps which use [email protected], which might
// > include Waterline v0.13.4. And all those things might rely on version 1 of the adapter API.
// > But Waterline v0.13.5 might support version 2 of the adapter API!! And while you can generally
// > trust semantic versioning to predict/understand userland API changes, be aware that the maximum
// > and/or minimum _adapter API version_ supported by Waterline could be incremented between major
// > version releases. When possible, compatibility for past versions of the adapter spec will be
// > maintained; just bear in mind that this is a _separate_ number, different from the NPM package
// > version. sails-hook-orm verifies this adapter API version when loading adapters to ensure
// > compatibility, so you should be able to rely on it to provide a good error message to the Sails
// > applications which use this adapter.
adapterApiVersion: 1,
// Default datastore configuration.
defaults: {},
addProvider: async function(accessKeyId, secretAccessKey) {
const providerChain = new AWS.CredentialProviderChain();
if (!!accessKeyId && !! secretAccessKey) {
providerChain.providers = [
new AWS.Credentials(accessKeyId, secretAccessKey),
...providerChain.providers,
];
}
try {
const credentials = await providerChain.resolvePromise();
return credentials;
} catch (err) {
console.log(`Unable to get credential providers: ${err.message}`);
}
return null;
},
updateCredentials: async function(datastoreConfig) {
const { accessKeyId, secretAccessKey, region, url } = datastoreConfig;
const credentials = await this.addProvider(accessKeyId, secretAccessKey);
dynamoDb = new AWS.DynamoDB({
credentials,
region,
endpoint: url
});
client = new AWS.DynamoDB.DocumentClient({ service: dynamoDb });
},
// ╔═╗═╗ ╦╔═╗╔═╗╔═╗╔═╗ ┌─┐┬─┐┬┬ ┬┌─┐┌┬┐┌─┐
// ║╣ ╔╩╦╝╠═╝║ ║╚═╗║╣ ├─┘├┬┘│└┐┌┘├─┤ │ ├┤
// ╚═╝╩ ╚═╩ ╚═╝╚═╝╚═╝ ┴ ┴└─┴ └┘ ┴ ┴ ┴ └─┘
// ┌┬┐┌─┐┌┬┐┌─┐┌─┐┌┬┐┌─┐┬─┐┌─┐┌─┐
// ││├─┤ │ ├─┤└─┐ │ │ │├┬┘├┤ └─┐
// ─┴┘┴ ┴ ┴ ┴ ┴└─┘ ┴ └─┘┴└─└─┘└─┘
// This allows outside access to this adapter's internal registry of datastore entries,
// for use in datastore methods like `.leaseConnection()`.
datastores: registeredDatastores,
//////////////////////////////////////////////////////////////////////////////////////////////////
// ██╗ ██╗███████╗███████╗ ██████╗██╗ ██╗ ██████╗██╗ ███████╗ //
// ██║ ██║██╔════╝██╔════╝██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔════╝ //
// ██║ ██║█████╗ █████╗ ██║ ╚████╔╝ ██║ ██║ █████╗ //
// ██║ ██║██╔══╝ ██╔══╝ ██║ ╚██╔╝ ██║ ██║ ██╔══╝ //
// ███████╗██║██║ ███████╗╚██████╗ ██║ ╚██████╗███████╗███████╗ //
// ╚══════╝╚═╝╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═════╝╚══════╝╚══════╝ //
// //
// Lifecycle adapter methods: //
// Methods related to setting up and tearing down; registering/un-registering datastores. //
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* ╦═╗╔═╗╔═╗╦╔═╗╔╦╗╔═╗╦═╗ ┌┬┐┌─┐┌┬┐┌─┐┌─┐┌┬┐┌─┐┬─┐┌─┐
* ╠╦╝║╣ ║ ╦║╚═╗ ║ ║╣ ╠╦╝ ││├─┤ │ ├─┤└─┐ │ │ │├┬┘├┤
* ╩╚═╚═╝╚═╝╩╚═╝ ╩ ╚═╝╩╚═ ─┴┘┴ ┴ ┴ ┴ ┴└─┘ ┴ └─┘┴└─└─┘
* Register a new datastore with this adapter. This usually involves creating a new
* connection manager (e.g. MySQL pool or MongoDB client) for the underlying database layer.
*
* > Waterline calls this method once for every datastore that is configured to use this adapter.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Dictionary} datastoreConfig Dictionary (plain JavaScript object) of configuration options for this datastore (e.g. host, port, etc.)
* @param {Dictionary} physicalModelsReport Experimental: The physical models using this datastore (keyed by "tableName"-- NOT by `identity`!). This may change in a future release of the adapter spec.
* @property {Dictionary} * [Info about a physical model using this datastore. WARNING: This is in a bit of an unusual format.]
* @property {String} primaryKey [the name of the primary key attribute (NOT the column name-- the attribute name!)]
* @property {Dictionary} definition [the physical-layer report from waterline-schema. NOTE THAT THIS IS NOT A NORMAL MODEL DEF!]
* @property {String} tableName [the model's `tableName` (same as the key this is under, just here for convenience)]
* @property {String} identity [the model's `identity`]
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done A callback to trigger after successfully registering this datastore, or if an error is encountered.
* @param {Error?}
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
registerDatastore: async function(
datastoreConfig,
physicalModelsReport,
done
) {
// Grab the unique name for this datastore for easy access below.
const datastoreName = datastoreConfig.identity;
// Some sanity checks:
if (!datastoreName) {
return done(
new Error(
'Consistency violation: A datastore should contain an "identity" property: a special identifier that uniquely identifies it across this app. This should have been provided by Waterline core! If you are seeing this message, there could be a bug in Waterline, or the datastore could have become corrupted by userland code, or other code in this adapter. If you determine that this is a Waterline bug, please report this at https://sailsjs.com/bugs.'
)
);
}
if (registeredDatastores[datastoreName]) {
return done(
new Error(
'Consistency violation: Cannot register datastore: `' +
datastoreName +
'`, because it is already registered with this adapter! This could be due to an unexpected race condition in userland code (e.g. attempting to initialize Waterline more than once), or it could be due to a bug in this adapter. (If you get stumped, reach out at https://sailsjs.com/support.)'
)
);
}
if (!datastoreConfig.region) {
return done(
new Error(
'Improper configuration of Dynamo Adaptor.\nRegion not provided.\nPlease verfiy your settings in config/datastores.js '
)
);
}
await this.updateCredentials(datastoreConfig);
try {
registeredDatastores[datastoreName] = {};
const tableList = await dynamoDb.listTables().promise();
const existingTables = new Set(tableList.TableNames);
const configuredTables = Object.keys(physicalModelsReport).map(key => {
const schema = physicalModelsReport[key];
const { tableName } = schema;
return tableName;
});
const $tableCreate = configuredTables
.map(tableName => util.getDynamoConfig(physicalModelsReport, tableName))
.map(schema =>
util.populateDataStore(registeredDatastores[datastoreName], schema)
)
.filter(schema => !existingTables.has(schema.tableName))
.map(util.prepareCreateTableQuery)
.map(queryObj => dynamoDb.createTable(queryObj).promise());
await Promise.all($tableCreate);
return done();
} catch (err) {
return done(Error(err));
}
},
/**
* ╔╦╗╔═╗╔═╗╦═╗╔╦╗╔═╗╦ ╦╔╗╔
* ║ ║╣ ╠═╣╠╦╝ ║║║ ║║║║║║║
* ╩ ╚═╝╩ ╩╩╚══╩╝╚═╝╚╩╝╝╚╝
* Tear down (un-register) a datastore.
*
* Fired when a datastore is unregistered. Typically called once for
* each relevant datastore when the server is killed, or when Waterline
* is shut down after a series of tests. Useful for destroying the manager
* (i.e. terminating any remaining open connections, etc.).
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The unique name (identity) of the datastore to un-register.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
teardown: function(datastoreName, done) {
return done();
},
//////////////////////////////////////////////////////////////////////////////////////////////////
// ██████╗ ███╗ ███╗██╗ //
// ██╔══██╗████╗ ████║██║ //
// ██║ ██║██╔████╔██║██║ //
// ██║ ██║██║╚██╔╝██║██║ //
// ██████╔╝██║ ╚═╝ ██║███████╗ //
// ╚═════╝ ╚═╝ ╚═╝╚══════╝ //
// (D)ata (M)anipulation (L)anguage //
// //
// DML adapter methods: //
// Methods related to manipulating records stored in the database. //
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* ╔═╗╦═╗╔═╗╔═╗╔╦╗╔═╗
* ║ ╠╦╝║╣ ╠═╣ ║ ║╣
* ╚═╝╩╚═╚═╝╩ ╩ ╩ ╚═╝
* Create a new record.
*
* (e.g. add a new row to a SQL table, or a new document to a MongoDB collection.)
*
* > Note that depending on the value of `query.meta.fetch`,
* > you may be expected to return the physical record that was
* > created (a dictionary) as the second argument to the callback.
* > (Otherwise, exclude the 2nd argument or send back `undefined`.)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore to perform the query on.
* @param {Dictionary} query The stage-3 query to perform.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* @param {Dictionary?}
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
create: async function(datastoreName, query, done) {
const TableName = query.using;
const record = query.newRecord;
const schema = registeredDatastores[datastoreName][TableName];
if (!schema) {
throw new Error({
err: `No table registered in models with ${TableName}`
});
}
try {
const Item = util.createDynamoItem(record, schema);
await client
.put({
TableName,
Item
})
.promise();
return done();
} catch (error) {
return done(Error(error));
}
},
/**
* ╔═╗╦═╗╔═╗╔═╗╔╦╗╔═╗ ╔═╗╔═╗╔═╗╦ ╦
* ║ ╠╦╝║╣ ╠═╣ ║ ║╣ ║╣ ╠═╣║ ╠═╣
* ╚═╝╩╚═╚═╝╩ ╩ ╩ ╚═╝ ╚═╝╩ ╩╚═╝╩ ╩
* Create multiple new records.
*
* > Note that depending on the value of `query.meta.fetch`,
* > you may be expected to return the array of physical records
* > that were created as the second argument to the callback.
* > (Otherwise, exclude the 2nd argument or send back `undefined`.)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore to perform the query on.
* @param {Dictionary} query The stage-3 query to perform.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* @param {Array?}
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
createEach: async function(datastoreName, query, done) {
const TableName = query.using;
const records = query.newRecords;
const schema = registeredDatastores[datastoreName][TableName];
if (!schema) {
throw new Error({
err: `No table registered in models with ${TableName}`
});
}
const Items = records.map(record => util.createDynamoItem(record, schema));
const batchedItems = util.createBatch(Items);
let $query = batchedItems.map(dataArr => {
const dQuery = { RequestItems: {} };
dQuery.RequestItems[TableName] = dataArr;
return client.batchWrite(dQuery).promise();
});
try {
await Promise.all($query);
return done();
} catch (err) {
return done(new Error(err));
}
},
/**
* ╦ ╦╔═╗╔╦╗╔═╗╔╦╗╔═╗
* ║ ║╠═╝ ║║╠═╣ ║ ║╣
* ╚═╝╩ ═╩╝╩ ╩ ╩ ╚═╝
* Update matching records.
*
* > Note that depending on the value of `query.meta.fetch`,
* > you may be expected to return the array of physical records
* > that were updated as the second argument to the callback.
* > (Otherwise, exclude the 2nd argument or send back `undefined`.)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore to perform the query on.
* @param {Dictionary} query The stage-3 query to perform.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* @param {Array?}
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
update: async function(datastoreName, query, done) {
// Look up the datastore entry (manager/driver/config).
const TableName = query.using;
const schema = registeredDatastores[datastoreName][TableName];
if (!schema) {
throw new Error({
err: `No table registered in models with ${TableName}`
});
}
try {
const record = query.valuesToSet;
const Item = util.createDynamoItem(record, schema);
// Here an assumption is made that update will always have keys in 0th index of where
// This will be true in every case but I am not sure
// Can be updated in future
let { where } = query.criteria;
let { and } = where;
if (Object.keys(where).length === 0) {
// when no search object is provided
throw new Error('No KeyCondition Provided');
} else if (!and && Object.keys(where).length === 1) {
// when user entered single value to search
and = [where];
}
let Key = and.reduce((prev, curr) => ({ ...prev, ...curr }), {});
let AttributeUpdates = util.createUpdateObject(Item);
const queryObj = {
TableName,
Key,
AttributeUpdates
};
await client.update(queryObj).promise();
} catch (err) {
return done(Error(err));
}
done();
},
/**
* ╔╦╗╔═╗╔═╗╔╦╗╦═╗╔═╗╦ ╦
* ║║║╣ ╚═╗ ║ ╠╦╝║ ║╚╦╝
* ═╩╝╚═╝╚═╝ ╩ ╩╚═╚═╝ ╩
* Destroy one or more records.
*
* > Note that depending on the value of `query.meta.fetch`,
* > you may be expected to return the array of physical records
* > that were destroyed as the second argument to the callback.
* > (Otherwise, exclude the 2nd argument or send back `undefined`.)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore to perform the query on.
* @param {Dictionary} query The stage-3 query to perform.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* @param {Array?}
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
destroy: async function(datastoreName, query, done) {
// Look up the datastore entry (manager/driver/config).
const dsEntry = registeredDatastores[datastoreName];
// Sanity check:
if (_.isUndefined(dsEntry)) {
return done(
new Error(
`Consistency violation: Cannot do that with datastore (${datastoreName})
because no matching datastore entry is registered in this adapter!
This is usually due to a race condition (e.g. a lifecycle callback still running after the ORM has been torn down),
or it could be due to a bug in this adapter. (If you get stumped, reach out at https://sailsjs.com/support.)"`
)
);
}
const TableName = query.using;
const schema = dsEntry[TableName];
if (!schema) {
throw new Error({
err: `No table registered in models with ${TableName}`
});
}
let { and } = query.criteria.where;
let Key = and.reduce((prev, curr) => ({ ...prev, ...curr }), {});
const queryObj = {
TableName,
Key
};
try {
await client.delete(queryObj).promise();
} catch (err) {
return done(Error(err));
}
done();
},
//////////////////////////////////////////////////////////////////////////////////////////////////
// ██████╗ ██████╗ ██╗ //
// ██╔══██╗██╔═══██╗██║ //
// ██║ ██║██║ ██║██║ //
// ██║ ██║██║▄▄ ██║██║ //
// ██████╔╝╚██████╔╝███████╗ //
// ╚═════╝ ╚══▀▀═╝ ╚══════╝ //
// (D)ata (Q)uery (L)anguage //
// //
// DQL adapter methods: //
// Methods related to fetching information from the database (e.g. finding stored records). //
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* ╔═╗╦╔╗╔╔╦╗
* ╠╣ ║║║║ ║║
* ╚ ╩╝╚╝═╩╝
* Find matching records.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore to perform the query on.
* @param {Dictionary} query The stage-3 query to perform.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* @param {Array} [matching physical records]
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
find: async function(datastoreName, query, done) {
// Look up the datastore entry (manager/driver/config).
const dsEntry = registeredDatastores[datastoreName];
if (_.isUndefined(dsEntry)) {
return done(
new Error(
'Consistency violation: Cannot do that with datastore (`' +
datastoreName +
'`) because no matching datastore entry is registered in this adapter! This is usually due to a race condition (e.g. a lifecycle callback still running after the ORM has been torn down), or it could be due to a bug in this adapter. (If you get stumped, reach out at https://sailsjs.com/support.)'
)
);
}
const TableName = query.using;
const schema = dsEntry[TableName];
const { where, limit, sort } = query.criteria;
if (sort && sort.length > 1) {
throw Error({ err: 'Cannot sort on more than one field' });
}
let ScanIndexForward = true;
if (sort.length === 1) {
let sortValue = Object.values(sort[0])[0];
if (sortValue === 'DESC') {
ScanIndexForward = false;
}
}
let { and } = where;
if (Object.keys(where).length === 0) {
// when no search object is provided
and = [];
} else if (!and && Object.keys(where).length === 1) {
// when user entered single value to search
and = [where];
}
const normalizedQuery = and.reduce(
(prev, curr) => ({ ...prev, ...curr }),
{}
);
const indexes = util.getIndexes(schema, normalizedQuery);
const conditions = util.prepareQueryConditions(normalizedQuery, indexes);
let LastEvaluatedKey = true;
const dynamoQuery = {
TableName,
ScanIndexForward,
...conditions
};
if (query.select) {
dynamoQuery.AttributesToGet = query.select;
} else {
dynamoQuery.AttributesToGet = Object.keys(schema);
}
if (limit && limit < 9007199254740991) {
dynamoQuery.Limit = limit;
}
let data;
if (indexes.type === 'localIndex') {
console.log('Local Index Query');
let IndexName = `${indexes.keys.hash}_local_index`;
dynamoQuery.IndexName = IndexName;
} else if (indexes.type === 'globalIndex') {
console.log('global index query');
let { hash } = indexes.keys;
let range = schema[hash].rangeKey;
if (!range) {
dynamoQuery.IndexName = `${hash}_global_index`;
} else {
dynamoQuery.IndexName = `${hash}_${range}_global_index`;
}
}
let finalData = [];
while (true) {
try {
if (indexes.type === 'scan') {
dynamoQuery.ScanFilter = util.deepClone(dynamoQuery.QueryFilter);
delete dynamoQuery.QueryFilter;
data = await client.scan(dynamoQuery).promise();
} else {
data = await client.query(dynamoQuery).promise();
}
} catch (err) {
return done(Error(err));
}
finalData = [...finalData, ...data.Items];
({ LastEvaluatedKey } = data);
if (!LastEvaluatedKey) {
break;
} else {
dynamoQuery.ExclusiveStartKey = LastEvaluatedKey;
}
}
const normalizedData = finalData.map(entry =>
util.normalizeData(entry, schema)
);
return done(null, normalizedData);
},
/**
* ╦╔═╗╦╔╗╔
* ║║ ║║║║║
* ╚╝╚═╝╩╝╚╝
* ┌─ ┌─┐┌─┐┬─┐ ┌┐┌┌─┐┌┬┐┬┬ ┬┌─┐ ┌─┐┌─┐┌─┐┬ ┬┬ ┌─┐┌┬┐┌─┐ ─┐
* │─── ├┤ │ │├┬┘ │││├─┤ │ │└┐┌┘├┤ ├─┘│ │├─┘│ ││ ├─┤ │ ├┤ ───│
* └─ └ └─┘┴└─ ┘└┘┴ ┴ ┴ ┴ └┘ └─┘ ┴ └─┘┴ └─┘┴─┘┴ ┴ ┴ └─┘ ─┘
* Perform a "find" query with one or more native joins.
*
* > NOTE: If you don't want to support native joins (or if your database does not
* > support native joins, e.g. Mongo) remove this method completely! Without this method,
* > Waterline will handle `.populate()` using its built-in join polyfill (aka "polypopulate"),
* > which sends multiple queries to the adapter and joins the results in-memory.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore to perform the query on.
* @param {Dictionary} query The stage-3 query to perform.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* @param {Array} [matching physical records, populated according to the join instructions]
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
join: function(datastoreName, query, done) {
// Look up the datastore entry (manager/driver/config).
var dsEntry = registeredDatastores[datastoreName];
// Sanity check:
if (_.isUndefined(dsEntry)) {
return done(
new Error(
'Consistency violation: Cannot do that with datastore (`' +
datastoreName +
'`) because no matching datastore entry is registered in this adapter! This is usually due to a race condition (e.g. a lifecycle callback still running after the ORM has been torn down), or it could be due to a bug in this adapter. (If you get stumped, reach out at https://sailsjs.com/support.)'
)
);
}
// Perform the query and send back a result.
//
// > TODO: Replace this setTimeout with real logic that calls
// > `done()` when finished. (Or remove this method from the
// > adapter altogether
setTimeout(() => {
return done(new Error('Adapter method (`join`) not implemented yet.'));
}, 16);
},
/**
* ╔═╗╔═╗╦ ╦╔╗╔╔╦╗
* ║ ║ ║║ ║║║║ ║
* ╚═╝╚═╝╚═╝╝╚╝ ╩
* Get the number of matching records.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore to perform the query on.
* @param {Dictionary} query The stage-3 query to perform.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* @param {Number} [the number of matching records]
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
count: function(datastoreName, query, done) {
// Look up the datastore entry (manager/driver/config).
var dsEntry = registeredDatastores[datastoreName];
// Sanity check:
if (_.isUndefined(dsEntry)) {
return done(
new Error(
'Consistency violation: Cannot do that with datastore (`' +
datastoreName +
'`) because no matching datastore entry is registered in this adapter! This is usually due to a race condition (e.g. a lifecycle callback still running after the ORM has been torn down), or it could be due to a bug in this adapter. (If you get stumped, reach out at https://sailsjs.com/support.)'
)
);
}
// Perform the query and send back a result.
//
// > TODO: Replace this setTimeout with real logic that calls
// > `done()` when finished. (Or remove this method from the
// > adapter altogether
setTimeout(() => {
return done(new Error('Adapter method (`count`) not implemented yet.'));
}, 16);
},
/**
* ╔═╗╦ ╦╔╦╗
* ╚═╗║ ║║║║
* ╚═╝╚═╝╩ ╩
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore to perform the query on.
* @param {Dictionary} query The stage-3 query to perform.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* @param {Number} [the sum]
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
sum: function(datastoreName, query, done) {
// Look up the datastore entry (manager/driver/config).
var dsEntry = registeredDatastores[datastoreName];
// Sanity check:
if (_.isUndefined(dsEntry)) {
return done(
new Error(
'Consistency violation: Cannot do that with datastore (`' +
datastoreName +
'`) because no matching datastore entry is registered in this adapter! This is usually due to a race condition (e.g. a lifecycle callback still running after the ORM has been torn down), or it could be due to a bug in this adapter. (If you get stumped, reach out at https://sailsjs.com/support.)'
)
);
}
// Perform the query and send back a result.
//
// > TODO: Replace this setTimeout with real logic that calls
// > `done()` when finished. (Or remove this method from the
// > adapter altogether
setTimeout(() => {
return done(new Error('Adapter method (`sum`) not implemented yet.'));
}, 16);
},
/**
* ╔═╗╦ ╦╔═╗
* ╠═╣╚╗╔╝║ ╦
* ╩ ╩ ╚╝ ╚═╝
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore to perform the query on.
* @param {Dictionary} query The stage-3 query to perform.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* @param {Number} [the average ("mean")]
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
avg: function(datastoreName, query, done) {
// Look up the datastore entry (manager/driver/config).
var dsEntry = registeredDatastores[datastoreName];
// Sanity check:
if (_.isUndefined(dsEntry)) {
return done(
new Error(
'Consistency violation: Cannot do that with datastore (`' +
datastoreName +
'`) because no matching datastore entry is registered in this adapter! This is usually due to a race condition (e.g. a lifecycle callback still running after the ORM has been torn down), or it could be due to a bug in this adapter. (If you get stumped, reach out at https://sailsjs.com/support.)'
)
);
}
// Perform the query and send back a result.
//
// > TODO: Replace this setTimeout with real logic that calls
// > `done()` when finished. (Or remove this method from the
// > adapter altogether
setTimeout(() => {
return done(new Error('Adapter method (`avg`) not implemented yet.'));
}, 16);
},
//////////////////////////////////////////////////////////////////////////////////////////////////
// ██████╗ ██████╗ ██╗ //
// ██╔══██╗██╔══██╗██║ //
// ██║ ██║██║ ██║██║ //
// ██║ ██║██║ ██║██║ //
// ██████╔╝██████╔╝███████╗ //
// ╚═════╝ ╚═════╝ ╚══════╝ //
// (D)ata (D)efinition (L)anguage //
// //
// DDL adapter methods: //
// Methods related to modifying the underlying structure of physical models in the database. //
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* ╔╦╗╔═╗╔═╗╦╔╗╔╔═╗
* ║║║╣ ╠╣ ║║║║║╣
* ═╩╝╚═╝╚ ╩╝╚╝╚═╝
* Build a new physical model (e.g. table/etc) to use for storing records in the database.
*
* (This is used for schema migrations.)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore containing the table to define.
* @param {String} tableName The name of the table to define.
* @param {Dictionary} definition The physical model definition (not a normal Sails/Waterline model-- log this for details.)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
define: function(datastoreName, tableName, definition, done) {
// Look up the datastore entry (manager/driver/config).
var dsEntry = registeredDatastores[datastoreName];
// Sanity check:
if (_.isUndefined(dsEntry)) {
return done(
new Error(
'Consistency violation: Cannot do that with datastore (`' +
datastoreName +
'`) because no matching datastore entry is registered in this adapter! This is usually due to a race condition (e.g. a lifecycle callback still running after the ORM has been torn down), or it could be due to a bug in this adapter. (If you get stumped, reach out at https://sailsjs.com/support.)'
)
);
}
// Define the physical model (e.g. table/etc.)
//
// > TODO: Replace this setTimeout with real logic that calls
// > `done()` when finished. (Or remove this method from the
// > adapter altogether
setTimeout(() => {
return done(new Error('Adapter method (`define`) not implemented yet.'));
}, 16);
},
/**
* ╔╦╗╦═╗╔═╗╔═╗
* ║║╠╦╝║ ║╠═╝
* ═╩╝╩╚═╚═╝╩
* Drop a physical model (table/etc.) from the database, including all of its records.
*
* (This is used for schema migrations.)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore containing the table to drop.
* @param {String} tableName The name of the table to drop.
* @param {Ref} unused Currently unused (do not use this argument.)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done Callback
* @param {Error?}
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
drop: function(datastoreName, tableName, unused, done) {
// Look up the datastore entry (manager/driver/config).
var dsEntry = registeredDatastores[datastoreName];
// Sanity check:
if (_.isUndefined(dsEntry)) {
return done(
new Error(
'Consistency violation: Cannot do that with datastore (`' +
datastoreName +
'`) because no matching datastore entry is registered in this adapter! This is usually due to a race condition (e.g. a lifecycle callback still running after the ORM has been torn down), or it could be due to a bug in this adapter. (If you get stumped, reach out at https://sailsjs.com/support.)'
)
);
}
// Drop the physical model (e.g. table/etc.)
//
// > TODO: Replace this setTimeout with real logic that calls
// > `done()` when finished. (Or remove this method from the
// > adapter altogether
setTimeout(() => {
return done(new Error('Adapter method (`drop`) not implemented yet.'));
}, 16);
},
/**
* ╔═╗╔═╗╔╦╗ ┌─┐┌─┐┌─┐ ┬ ┬┌─┐┌┐┌┌─┐┌─┐
* ╚═╗║╣ ║ └─┐├┤ │─┼┐│ │├┤ ││││ ├┤
* ╚═╝╚═╝ ╩ └─┘└─┘└─┘└└─┘└─┘┘└┘└─┘└─┘
* Set a sequence in a physical model (specifically, the auto-incrementing
* counter for the primary key) to the specified value.
*
* (This is used for schema migrations.)
*
* > NOTE - If your adapter doesn't support sequence entities (like PostgreSQL),
* > you should remove this method.
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {String} datastoreName The name of the datastore containing the table/etc.
* @param {String} sequenceName The name of the sequence to update.
* @param {Number} sequenceValue The new value for the sequence (e.g. 1)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Function} done
* @param {Error?}
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
setSequence: function(datastoreName, sequenceName, sequenceValue, done) {
// Look up the datastore entry (manager/driver/config).
var dsEntry = registeredDatastores[datastoreName];
// Sanity check:
if (_.isUndefined(dsEntry)) {
return done(
new Error(
'Consistency violation: Cannot do that with datastore (`' +
datastoreName +
'`) because no matching datastore entry is registered in this adapter! This is usually due to a race condition (e.g. a lifecycle callback still running after the ORM has been torn down), or it could be due to a bug in this adapter. (If you get stumped, reach out at https://sailsjs.com/support.)'
)
);
}
// Update the sequence.
//
// > TODO: Replace this setTimeout with real logic that calls
// > `done()` when finished. (Or remove this method from the
// > adapter altogether
setTimeout(() => {
return done(
new Error('Adapter method (`setSequence`) not implemented yet.')
);
}, 16);
}
};