forked from dohzoh/sails-dynamodb
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
1351 lines (1081 loc) · 40.4 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
/**
* Module Dependencies
*/
// ...
// e.g.
// var _ = require('lodash');
// var mysql = require('node-mysql');
// ...
var Vogels = require('vogels');
var AWS = Vogels.AWS;
var _ = require('lodash');
var DynamoDB = false;
var filters = {
//?where={"name":{"null":true}}
null: false,
//?where={"name":{"notNull":true}}
notNull: false,
//?where={"name":{"equals":"firstName lastName"}}
equals: true,
//?where={"name":{"ne":"firstName lastName"}}
ne: true,
//?where={"name":{"lte":"firstName lastName"}}
lte: true,
//?where={"name":{"lt":"firstName lastName"}}
lt: true,
//?where={"name":{"gte":"firstName lastName"}}
gte: true,
//?where={"name":{"gt":"firstName lastName"}}
gt: true,
//?where={"name":{"contains":"firstName lastName"}}
contains: true,
//?where={"name":{"contains":"firstName lastName"}}
notContains: true,
//?where={"name":{"beginsWith":"firstName"}}
beginsWith: true,
//?where={"name":{"in":["firstName lastName", "another name"]}}
in: true,
//?where={"name":{"between":["firstName", "lastName"]}}
between: true
};
/**
* Sails Boilerplate Adapter
*
* 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 load them at the top of the file with other dependencies. e.g. var update = `require('./lib/update')`;
*/
module.exports = (function () {
// Hold connections for this adapter
var connections = {};
// You'll want to maintain a reference to each collection
// (aka model) that gets registered with this adapter.
var _collectionReferences = {};
var _vogelsReferences = {};
var _definedTables = {};
// You may also want to store additional, private data
// per-collection (esp. if your data store uses persistent
// connections).
//
// Keep in mind that models can be configured to use different databases
// within the same app, at the same time.
//
// i.e. if you're writing a MariaDB adapter, you should be aware that one
// model might be configured as `host="localhost"` and another might be using
// `host="foo.com"` at the same time. Same thing goes for user, database,
// password, or any other config.
//
// You don't have to support this feature right off the bat in your
// adapter, but it ought to get done eventually.
//
// Sounds annoying to deal with...
// ...but it's not bad. In each method, acquire a connection using the config
// for the current model (looking it up from `_modelReferences`), establish
// a connection, then tear it down before calling your method's callback.
// Finally, as an optimization, you might use a db pool for each distinct
// connection configuration, partioning pools for each separate configuration
// for your adapter (i.e. worst case scenario is a pool for each model, best case
// scenario is one single single pool.) For many databases, any change to
// host OR database OR user OR password = separate pool.
var _dbPools = {};
var adapter = {
identity: 'sails-dynamodb',
pkFormat: 'string',
keyId: 'id',
// Set to true if this adapter supports (or requires) things like data types, validations, keys, etc.
// If true, the schema for models using this adapter will be automatically synced when the server starts.
// Not terribly relevant if your data store is not SQL/schemaful.
// This doesn't make sense for dynamo, where the schema parts are locked-down during table creation.
syncable: false,
// Default configuration for collections
// (same effect as if these properties were included at the top level of the model definitions)
defaults: {
accessKeyId: null,
secretAccessKey: null,
region: 'us-west-1',
// For example:
// port: 3306,
// host: 'localhost',
// schema: true,
// ssl: false,
// customThings: ['eh']
// If setting syncable, you should consider the migrate option,
// which allows you to set how the sync will be performed.
// It can be overridden globally in an app (config/adapters.js)
// and on a per-model basis.
//
// IMPORTANT:
// `migrate` is not a production data migration solution!
// In production, always use `migrate: safe`
//
// drop => Drop schema and data, then recreate it
// alter => Drop/add columns as necessary.
// safe => Don't change anything (good for production DBs)
//Indices currently never change in dynamo
migrate: 'safe',
// schema: false
},
_createModel: function (collectionName) {
var collection = _collectionReferences[collectionName];
// Attrs with primaryKeys
var primaryKeys = _.pick(collection.definition, function(attr) { return !!attr.primaryKey } );
var primaryKeyNames =_.keys(primaryKeys);
if (primaryKeyNames.length < 1 || primaryKeyNames.length > 2) {
throw new Error('Must have one or two primary key attributes.');
}
// One primary key, then it's a hash
if (primaryKeyNames.length == 1) {
collection.definition[primaryKeyNames[0]].primaryKey = 'hash';
}
// Vogels adds an 's'. So let's remove an 's'.
var vogelsCollectionName = collectionName[collectionName.length-1] === 's' ?
collectionName.slice(0, collectionName.length-1) :
collectionName;
var vogelsModel = Vogels.define(vogelsCollectionName, function (schema) {
var columns = collection.definition;
var indices = {};
// set columns
for (var columnName in columns) {
var attributes = columns[columnName];
if (typeof attributes !== "function") {
// Add column to Vogel model
adapter._setColumnType(schema, columnName, attributes);
// Save set indices
var index;
var indexParts;
var indexName;
var indexType;
if ("index" in attributes && attributes.index !== 'secondary') {
index = attributes.index;
if (_.isArray(index)){
index.forEach((oneIndex) => {
indexParts = adapter._parseIndex(oneIndex, columnName);
indexName = indexParts[0];
indexType = indexParts[1];
if (typeof indices[indexName] === 'undefined') {
indices[indexName] = {};
}
indices[indexName][indexType] = columnName;
});
}else{
indexParts = adapter._parseIndex(index, columnName);
indexName = indexParts[0];
indexType = indexParts[1];
if (typeof indices[indexName] === 'undefined') {
indices[indexName] = {};
}
indices[indexName][indexType] = columnName;
}
}
}
}
// Set global secondary indices
for (indexName in indices) {
schema.globalIndex(indexName, indices[indexName]);
}
});
// Cache Vogels model
_vogelsReferences[collectionName] = vogelsModel;
Vogels.createTables(function (err) {
if (err) {
console.log('Error creating tables: ', err);
} else {
console.log('Tables have been created');
}
});
return vogelsModel;
},
_getModel: function(collectionName) {
return _vogelsReferences[collectionName] || this._createModel(collectionName);
},
_getPrimaryKeys: function (collectionName) {
var lodash = _;
var collection = _collectionReferences[collectionName];
var maps = lodash.mapValues(collection.definition, "primaryKey");
// console.log(results);
var list = lodash.pick(maps, function (value, key) {
return typeof value !== "undefined";
});
var primaryKeys = lodash.keys(list);
return primaryKeys;
},
_keys: function (collectionName) {
var lodash = _;
var collection = _collectionReferences[collectionName];
var list = lodash.pick(collection.definition, function (value, key) {
return (typeof value !== "undefined");
});
return lodash.keys(list);
},
_indexes: function (collectionName) {
var lodash = _;
var collection = _collectionReferences[collectionName];
var list = lodash.pick(collection.definition, function (value, key) {
return ("index" in value && value.index === true)
});
return lodash.keys(list);
},
// index: 'secondary'
_getLocalIndices: function(collectionName) {
},
// index: 'indexName-fieldType' (i.e. 'users-hash' and 'users-range')
_getGlobalIndices: function(collectionName) {
},
_parseIndex: function(index, columnName) {
// Two helpers
var stringEndsWith = function(str, needle) {
if (str.indexOf(needle) !== -1 &&
str.indexOf(needle) === str.length-needle.length) {
return true;
} else {
return false;
}
}
var removeSuffixFromString = function(str, suffix) {
if (stringEndsWith(str, suffix)) {
return str.slice(0, str.length-suffix.length);
} else {
return str;
}
}
var indexName;
var indexType;
if (index === true) {
indexName = columnName;
indexType = 'hashKey';
} else if (stringEndsWith(index, '-hash')) {
indexName = removeSuffixFromString(index, '-hash');
indexType = 'hashKey';
} else if (stringEndsWith(index, '-range')) {
indexName = removeSuffixFromString(index, '-range');
indexType = 'rangeKey';
} else {
throw new Error('Index must be a hash or range.');
}
return [indexName, indexType];
},
/**
*
* This method runs when a model is initially registered
* at server-start-time. This is the only required method.
*
* @param string collection [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
registerConnection: function (connection, collections, cb) {
if (!connection.identity) return cb(Errors.IdentityMissing);
if (connections[connection.identity]) return cb(Errors.IdentityDuplicate);
try {
AWS.config.update({
"accessKeyId": connection.accessKeyId,
"secretAccessKey": connection.secretAccessKey,
"region": connection.region,
"endpoint": connection.endPoint,
"logger": connection.logger
});
} catch (e) {
e.message = e.message + ". Please make sure you added the right keys to your adapter config";
return cb(e)
}
// Keep a reference to these collections
_collectionReferences = collections;
// Create Vogels models for the collections
_.forOwn(collections, function(coll, collName) {
adapter._createModel(collName);
});
cb();
},
/**
* Fired when a model is unregistered, typically when the server
* is killed. Useful for tearing-down remaining open connections,
* etc.
*
* @param {Function} cb [description]
* @return {[type]} [description]
*/
teardown: function (connection, cb) {
cb();
},
/**
*
* REQUIRED method if integrating with a schemaful
* (SQL-ish) database.
*
* @param {[type]} collectionName [description]
* @param {[type]} definition [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
define: function (connection, collectionName, definition, cb) {
//sails.log.silly("adaptor::define");
//sails.log.silly("::collectionName", collectionName);
//sails.log.silly("::definition", definition);
//sails.log.silly("::model", adapter._getModel(collectionName));
// If you need to access your private data for this collection:
var collection = _collectionReferences[collectionName];
if (!_definedTables[collectionName]) {
var table = adapter._getModel(collectionName);
_definedTables[collectionName] = table;
Vogels.createTables({
collectionName: {readCapacity: 1, writeCapacity: 1}
}, function (err) {
if (err) {
//sails.log.error('Error creating tables', err);
cb(err);
}
else {
// console.log('table are now created and active');
cb();
}
});
}
else {
cb();
}
// Define a new "table" or "collection" schema in the data store
},
/**
*
* REQUIRED method if integrating with a schemaful
* (SQL-ish) database.
*
* @param {[type]} collectionName [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
describe: function (connection, collectionName, cb) {
//sails.log.silly("adaptor::describe");
//console.log("::connection",connection);
//console.log("::collection",collectionName);
// If you need to access your private data for this collection:
var collection = _collectionReferences[collectionName];
//console.log("::collection.definition",collection.definition);
// Respond with the schema (attributes) for a collection or table in the data store
var attributes = {};
// extremly simple table names
var tableName = collectionName.toLowerCase() + 's'; // 's' is vogels spec
var Endpoint = collection.connections[connection]['config']['endPoint'];
if (DynamoDB === false) {
DynamoDB = new AWS.DynamoDB(
Endpoint ? {endpoint: new AWS.Endpoint(Endpoint)}
: null
);
if (Endpoint)
Vogels.dynamoDriver(DynamoDB);
}
DynamoDB.describeTable({TableName: tableName}, function (err, res) {
if (err) {
if ('code' in err && err['code'] === 'ResourceNotFoundException') {
cb();
}
else {
//sails.log.error('Error describe tables' + __filename, err);
cb(err);
}
// console.log(err); // an error occurred
}
else {
// console.log(data); // successful response
cb();
}
});
},
/**
*
*
* REQUIRED method if integrating with a schemaful
* (SQL-ish) database.
*
* @param {[type]} collectionName [description]
* @param {[type]} relations [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
drop: function (connection, collectionName, relations, cb) {
//sails.log.silly("adaptor::drop", collectionName);
// If you need to access your private data for this collection:
var collection = _collectionReferences[collectionName];
//sails.log.error('drop: not supported')
// Drop a "table" or "collection" schema from the data store
cb();
},
// OVERRIDES NOT CURRENTLY FULLY SUPPORTED FOR:
//
// alter: function (collectionName, changes, cb) {},
// addAttribute: function(collectionName, attrName, attrDef, cb) {},
// removeAttribute: function(collectionName, attrName, attrDef, cb) {},
// alterAttribute: function(collectionName, attrName, attrDef, cb) {},
// addIndex: function(indexName, options, cb) {},
// removeIndex: function(indexName, options, cb) {},
/**
*
* REQUIRED method if users expect to call Model.find(), Model.findOne(),
* or related.
*
* You should implement this method to respond with an array of instances.
* Waterline core will take care of supporting all the other different
* find methods/usages.
*
* @param {[type]} collectionName [description]
* @param {[type]} options [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
find: function (connection, collectionName, options, cb) {
//sails.log.silly("adaptor::find", collectionName);
//sails.log.silly("::option", options);
var collection = _collectionReferences[collectionName],
model = adapter._getModel(collectionName),
query = null,
error;
// Options object is normalized for you:
//
// options.where
// options.limit
// options.skip
// options.
// Filter, paginate, and sort records from the datastore.
// You should end up w/ an array of objects as a result.
// If no matches were found, this will be an empty array.
if (options && 'where' in options && _.isObject(options.where)) {
var wheres = options.where,
whereExt = this._getSubQueryWhereConditions(options),
indexing = adapter._whichIndex(collectionName, ((whereExt) ? whereExt : wheres )),
hash = indexing.hash,
range = indexing.range,
indexName = indexing.index,
scanning = false;
if (indexing) {
// console.log("USING INDEX")
// console.log(indexing);
query = model.query(options.where[hash])
delete options.where[hash];
if (indexName && indexName != 'primary') {
query.usingIndex(indexName);
}
if (range) {
error = adapter._applyQueryFilter(query, 'where', range, options.where[range]);
if (error) return cb(error);
delete options.where[range];
}
} else {
scanning = true;
query = model.scan();
}
var queryOp = scanning ? 'where' : 'filter';
for (var key in options.where) {
// Using startKey?
if (key == 'startKey') {
try {
if (_.isString(options.where.startKey)){
query.startKey(JSON.parse(options.where[key]));
}else{
query.startKey(options.where.startKey);
}
} catch (e) {
return cb("Wrong start key format :" + e.message);
}
} else {
var condition = (whereExt) ? whereExt : options.where[key];
if (whereExt) {
for (var subKey in condition) {
error = adapter._applyQueryFilter(query, queryOp, subKey, condition[subKey]);
if (error) return cb(error);
}
options.where = whereExt;
} else {
error = adapter._applyQueryFilter(query, queryOp, key, condition);
if (error) return cb(error);
}
}
}
}
query = adapter._searchCondition(query, options, model);
this._findQuery(adapter, collection, query, false, cb);
},
/**
* _findQuery
* @description :: Return result if found. If not and the developer set a limit
on the number of entries to return, then we must keep
scanning the DB until the end is reached or until a result is returned
* @author :: Matt McCarty (https://github.com/mattmccarty)
* @param :: object adapter - Current sails-dynamodb instance
* @param :: object collection - Collection reference
* @param :: object query - Current query
* @param :: object startKey - Contains primary key of record where the search should start
* @param :: function callback
* @return :: callback(err, results)
*/
_findQuery: function(adapter, collection, query, startKey, cb) {
var _self = this;
if (startKey) {
query.request = query.request || {};
query.request.ExclusiveStartKey = startKey;
}
query.exec(function(err, res) {
if (!err) {
// The developer requested a specific number of items, so loop over each DB entry
// until the end of the db table is reached or until a result is found
if (res && res.Count <= 0 && res.LastEvaluatedKey && res.LastEvaluatedKey.id) {
var lastKey = {
id: { S: res.LastEvaluatedKey.id },
}
return adapter._findQuery(adapter, collection, query, lastKey, cb);
}
adapter._valueDecode(collection.definition, res.attrs);
cb(null, adapter._resultFormat(res));
}
else {
cb(err);
}
});
},
/**
* _getSubQueryWhereConditions
* @description :: Handle where objects that contain subquery arrays (i.e: and: [], or: [], etc).
* For consistency, This is useful when using dynamo and mongo data connections
* in the same project.
* @author :: Matt McCarty (https://github.com/mattmccarty)
* @param :: object
* @return :: Object filled with 'where' values or false
*/
_getSubQueryWhereConditions: function(options) {
var wheresCurrent = _.keys(options.where),
conditionalOperator = 'AND',
wheres = [],
whereExt = false,
count = 0;
for (var key in wheresCurrent) {
var where = options.where[wheresCurrent[key]];
if (!_.isArray(where)) {
wheres.push(wheresCurrent[key]);
continue;
}
if (typeof wheresCurrent[key] === 'string' && wheresCurrent[key].toUpperCase() === 'OR') {
conditionalOperator = 'OR';
}
for (var arrKey in where) {
if (typeof where[arrKey] !== 'object') {
continue;
}
var subKeys = _.keys(where[arrKey]);
// Concat unique keys
wheres = _.union(wheres, subKeys);
for (var subKey in subKeys) {
if (!whereExt) whereExt = {};
whereExt[subKeys[subKey]] = where[arrKey][subKeys[subKey]];
count++;
}
}
}
if (whereExt && count > 1) {
whereExt.ConditionalOperator = conditionalOperator;
}
return whereExt;
},
_applyQueryFilter: function(query, op, key, condition) {
try {
if (key === 'ConditionalOperator' && query.request) {
query.request.ConditionalOperator = condition;
} else if (_.isString(condition) || _.isNumber(condition)) {
query[op](key).equals(condition);
} else if (_.isArray(condition)) {
query[op](key).in(condition);
} else if (_.isObject(condition)) {
var filter = _.keys(condition)[0];
if (filter in filters) {
query[op](key)[filter](filters[filter] ? condition[filter] : null);
} else {
throw new Error("Wrong filter given :" + filter);
}
} else {
throw new Error("Wrong filter given :" + filter);
}
} catch (e) {
return e;
}
},
// Return {index: 'name', hash: 'field1', range:'field2'}
// Primary hash and range > primary hash and secondary range > global secondary hash and range
// > primary hash > global secondary hash > no index/primary
_whichIndex: function(collectionName, fields) {
var columns = _collectionReferences[collectionName].definition;
var primaryHash = false;
var primaryRange = false;
var secondaryRange = false;
var globalHash = false;
var globalRange = false;
var globalIndexName;
// holds all index info from fields
var indices = {};
// temps for loop
var fieldName;
var column;
var indexInfo;
var indexName;
var indexType;
if (!(_.isArray(fields))){
fields = Object.keys(fields);
}
// console.log("FIELDS")
// console.log(fields);
for (var i = 0; i < fields.length; i++) {
fieldName = fields[i];
column = columns[fieldName];
if (column === undefined){ // happens in the case of startKey
continue;
}
// set primary hash
if (column.primaryKey){
if (column.primaryKey === true || column.primaryKey === 'hash'){
primaryHash = fieldName;
}else if (column.primaryKey === 'range') {
primaryRange = fieldName;
}
}
// using secondary or GSIs
if (column.index){
// console.log("COLUMN.INDEX")
// console.log(column.index)
if (_.isArray(column.index)){
column.index.forEach((oneIndex) => {
if (oneIndex === 'secondary'){
secondaryRange = fieldName;
}else{
indexInfo = adapter._parseIndex(oneIndex, fieldName);
indexName = indexInfo[0];
indexType = indexInfo[1];
if (typeof indices[indexName] === 'undefined') {
indices[indexName] = {};
}
indices[indexName][indexType] = fieldName;
}
});
// throw new Error(`No support yet for multiple non-primary indexes, ${fieldName} = ${column.index}`);
}else if (column.index === 'secondary'){
secondaryRange = fieldName;
}else{
indexInfo = adapter._parseIndex(column.index, fieldName);
indexName = indexInfo[0];
indexType = indexInfo[1];
if (typeof indices[indexName] === 'undefined') {
indices[indexName] = {};
}
indices[indexName][indexType] = fieldName;
}
}
}
// console.log("INDICES")
// console.log(indices)
// set global secondary hash info
var indicesHashed;
var indicesRanged;
// pick out those with just a hash key
var indicesHashed = _.pick(indices, function(ind) {
return !!ind.hashKey && !ind.rangeKey;
});
// pick out those with a hash and a range key
var indicesRanged = _.pick(indices, function(ind) {
return !!ind.hashKey && !!ind.rangeKey;
});
// found a good ranged global secondary index?
if (!_.isEmpty(indicesRanged)) {
globalIndexName = Object.keys(indicesRanged)[0];
globalHash = indicesRanged[globalIndexName].hashKey;
globalRange = indicesRanged[globalIndexName].rangeKey;
} else if (!_.isEmpty(indicesHashed)) {
globalIndexName = Object.keys(indicesHashed)[0];
globalHash = indicesHashed[globalIndexName].hashKey;
}
if (primaryHash && primaryRange) {
return {
index: 'primary',
hash: primaryHash,
range: primaryRange
}
} else if (primaryHash && secondaryRange) {
return {
index: secondaryRange+'Index', // per Vogels
hash: primaryHash,
range: secondaryRange
}
} else if (globalHash && globalRange) {
return {
index: globalIndexName,
hash: globalHash,
range: globalRange
}
} else if (primaryHash) {
return {
index: 'primary',
hash: primaryHash
}
} else if (globalHash) {
return {
index: globalIndexName,
hash: globalHash
}
} else {
return false;
}
},
/**
* search condition
* @param query
* @param options
* @returns {*}
* @private
*/
_searchCondition: function (query, options, model) {
if (!query) {
query = model.scan();
}
if (!options) {
return query;
}
if ('sort' in options) {
//according to http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#DDB-Query-request-ScanIndexForward
var sort = _.keys(options.sort)[0];
if (sort == 1) {
query.ascending();
}
else if (sort == -1) {
query.descending();
}
}
if ('limit' in options) {
query.limit(options.limit);
} else {
query.loadAll();
}
if ('select' in options) {
if (_.isString(options.select)) {
query = query.attributes([options.select]);
} else {
query = query.attributes(options.select);
}
}
return query;
},
/**
*
* REQUIRED method if users expect to call Model.create() or any methods
*
* @param {[type]} collectionName [description]
* @param {[type]} values [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/create: function (connection, collectionName, values, cb) {
//sails.log.silly("adaptor::create", collectionName);
//sails.log.silly("values", values);
//console.log("collection", _modelReferences[collectionName]);
var Model = adapter._getModel(collectionName);
// If you need to access your private data for this collection:
var collection = _collectionReferences[collectionName];
adapter._valueEncode(collection.definition, values);
// Create a single new model (specified by `values`)
var current = Model.create(values, function (err, res) {
if (err) {
//sails.log.error(__filename + ", create error:", err);
err.stack = '';
cb(err);
}
else {
adapter._valueDecode(collection.definition, res.attrs);
// console.log('add model data',res.attrs);
// Respond with error or the newly-created record.
cb(null, res.attrs);
}
});
},