This repository is currently being migrated. It's locked while the migration is in progress.
forked from keinu/dynamodb-driver
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
777 lines (622 loc) · 18.5 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
const Promise = require("bluebird");
const { v4: uuidv4 } = require("uuid");
const AWS = require("aws-sdk");
AWS.config.setPromisesDependency(Promise);
const utils = require("./utils");
global.__basePath = process.env.PWD;
module.exports = function (dynamoDbOptions) {
"use strict";
const dynamodb = new AWS.DynamoDB(dynamoDbOptions);
const query = function (table, conditions, index, options) {
const params = {
TableName: table
};
if (index) {
params.IndexName = index;
}
// Legacy KeyConditions are in use
if (conditions.constructor === Array) {
const keys = {};
conditions.forEach(function (condition) {
keys[condition.key] = {
ComparisonOperator: condition.operator,
AttributeValueList: [utils.itemize(condition.value)]
};
});
params.KeyConditions = keys;
}
// KeyConditionExpression are in use
if (conditions.constructor === Object) {
params.KeyConditionExpression = conditions.KeyConditionExpression;
params.ExpressionAttributeNames = conditions.ExpressionAttributeNames;
const ExpressionAttributeValues = {};
const values = conditions.ExpressionAttributeValues;
for (const property in values) {
if (!values.hasOwnProperty(property)) {
continue;
}
ExpressionAttributeValues[property] = utils.itemize(values[property]);
}
params.ExpressionAttributeValues = ExpressionAttributeValues;
}
if (options && options.reverse) {
params.ScanIndexForward = false;
}
if (options && options.limit) {
params.Limit = options.limit;
}
if (options && options.filter) {
const queryFilter = {};
options.filter.forEach(function (condition) {
queryFilter[condition.key] = {
ComparisonOperator: condition.operator,
AttributeValueList: [utils.itemize(condition.value)]
};
});
params.QueryFilter = queryFilter;
}
if (options && options.projection && options.projection.length) {
params.ProjectionExpression = options.projection.map(p => `#${p}`).join(",");
params.ExpressionAttributeNames = {};
options.projection.forEach(function (p) {
params.ExpressionAttributeNames[`#${p}`] = p;
});
}
if (options && options.paginate) {
const items = [];
const paginate = function (lastItem) {
params.Limit = options.paginate;
if (lastItem) {
params.ExclusiveStartKey = lastItem;
}
return dynamodb
.query(params)
.promise()
.then(function (data) {
data.Items.forEach(function (item) {
items.push(utils.deitemize(item));
});
if (data.LastEvaluatedKey) {
return paginate(data.LastEvaluatedKey);
}
return items;
});
};
return paginate();
}
if (options && options.limit) {
params.Limit = options.limit;
}
if (options && options.exclusiveStartKey) {
params.ExclusiveStartKey = options.exclusiveStartKey;
}
return dynamodb
.query(params)
.promise()
.then(function (data) {
const items = [];
data.Items.forEach(function (item) {
items.push(utils.deitemize(item));
});
// return an object with the items and
// last evaluated key if the option is specified.
if (options && options.getLastEvaluatedKey) {
return {
items,
lastEvaluatedKey: data.LastEvaluatedKey
};
}
return items;
});
};
const list = function (table, conditions, options) {
const params = {
TableName: table
};
const keys = {};
conditions = conditions || [];
conditions.forEach(function (condition) {
keys[condition.key] = {
ComparisonOperator: condition.operator,
AttributeValueList: [utils.itemize(condition.value)]
};
});
if (options && options.projection && options.projection.length) {
params.ProjectionExpression = options.projection.map(p => `#${p}`).join(",");
params.ExpressionAttributeNames = {};
options.projection.forEach(function (p) {
params.ExpressionAttributeNames[`#${p}`] = p;
});
}
if (Object.keys(keys).length) {
params.ScanFilter = keys;
}
if (options && options.paginate) {
const items = [];
const paginate = function (lastItem) {
params.Limit = options.paginate;
if (lastItem) {
params.ExclusiveStartKey = lastItem;
}
return dynamodb
.scan(params)
.promise()
.then(function (data) {
data.Items.forEach(function (item) {
items.push(utils.deitemize(item));
});
if (data.LastEvaluatedKey) {
return paginate(data.LastEvaluatedKey);
}
return items;
});
};
return paginate();
}
if (options && options.limit) {
params.Limit = options.limit;
}
if (options && options.exclusiveStartKey) {
params.ExclusiveStartKey = options.exclusiveStartKey;
}
return dynamodb
.scan(params)
.promise()
.then(function (data) {
const items = [];
data.Items.forEach(function (item) {
items.push(utils.deitemize(item));
});
// return an object with the items and
//last evaluated key if the option is specified.
if (options && options.getLastEvaluatedKey) {
return {
items,
lastEvaluatedKey: data.LastEvaluatedKey
};
}
return items;
});
};
const get = function (table, id) {
const params = {
TableName: table,
Key: {
id: {
S: id
}
}
};
return dynamodb
.getItem(params)
.promise()
.then(function (data) {
return utils.deitemize(data.Item);
});
};
const getItems = function (table, ids, options) {
if (ids.constructor !== Array) {
throw Error("ids is not an Array");
}
// Don't touch the original items, work on a copy
const documents = ids.slice(0);
if (!documents || documents.length === 0) {
return Promise.resolve([]);
}
let items = [];
options = options || {};
const maxGetItems = 100; // Currently 25 on AWS
// For fibonacci exponential backoff
let previous = 1;
let anteprevious = 1;
let delay = 0;
// For reverting the back-off
const series = [0];
const getDocuments = function (Requests) {
// Constructs the request
const params = {
RequestItems: {}
};
params.RequestItems[table] = Requests;
return dynamodb
.batchGetItem(params)
.promise()
.then(function (batchResponse) {
const docs = batchResponse.Responses[table].map(i => utils.deitemize(i));
items = items.concat(docs);
if (
batchResponse.UnprocessedKeys[table] &&
Array.isArray(batchResponse.UnprocessedKeys[table].Keys)
) {
console.log(
"%s unprocessed items",
batchResponse.UnprocessedKeys[table].Keys.length
);
let delayAction;
if (options.noDelay) {
delayAction = Promise.resolve();
} else {
// Keep the list of delays
series.push(delay);
delay = previous + anteprevious;
anteprevious = previous;
previous = delay;
console.log("Delaying next batch, %d seconds", delay);
delayAction = Promise.delay(delay * 1000);
}
return delayAction.then(function () {
return getDocuments(batchResponse.UnprocessedKeys[table]);
});
}
// Revert the back of to the latest position
// Not putting the back off to 0 to keep playing nicely
if (series.length > 1) {
previous = series.pop() || 0;
}
})
.catch(function (err) {
if (err.code === "ProvisionedThroughputExceededException") {
console.log(
"Provisioned Capacity error when getting items, delaying 15 seconds"
);
return Promise.delay(15 * 1000).then(function () {
return getDocuments(Requests);
});
}
console.log(err);
throw err;
});
};
// Returns a promise of the write operation
const getOperation = function (documentsSet) {
const keys = documentsSet.map(function (document) {
if (!options.keys) {
// By default, the parameters are an array of ids
return {
id: utils.itemize(document)
};
}
// options.keys is specified as an array of values for hash or hash & key
return options.keys.reduce(function (acc, key) {
acc[key] = utils.itemize(document[key]);
return acc;
}, {});
});
const params = {
ConsistentRead: options.consistentRead || false,
Keys: keys
};
if (options && Array.isArray(options.projection)) {
params.ProjectionExpression = options.projection.map(p => `#${p}`).join(",");
params.ExpressionAttributeNames = options.projection.reduce(
(attributeNames, attributeName) => {
attributeNames[`#${attributeName}`] = attributeName;
return attributeNames;
},
{}
);
}
return getDocuments(params);
};
// Contains arrays of $maxWriteItems items to save
const documentsToGet = [];
while (documents.length) {
documentsToGet.push(documents.splice(0, maxGetItems));
}
// Wait for all promises to be fulfilled one by one
return Promise.each(documentsToGet, getOperation).then(() => items);
};
const create = function (table, document, conditions) {
if (!document.id) {
document.id = uuidv4();
}
const item = {};
Object.keys(document).forEach(function (key) {
item[key] = utils.itemize(document[key]);
});
const params = {
ReturnConsumedCapacity: "TOTAL",
ReturnItemCollectionMetrics: "SIZE",
ReturnValues: "ALL_OLD",
TableName: table,
Item: item
};
// KeyConditionExpression are in use
if (conditions && conditions.constructor === Object) {
params.ConditionExpression = conditions.ConditionExpression;
if (conditions.ExpressionAttributeNames) {
params.ExpressionAttributeNames = conditions.ExpressionAttributeNames;
}
const ExpressionAttributeValues = {};
const values = conditions.ExpressionAttributeValues;
for (const p in values) {
if (!values.hasOwnProperty(p)) {
continue;
}
ExpressionAttributeValues[p] = utils.itemize(values[p]);
}
params.ExpressionAttributeValues = ExpressionAttributeValues;
}
return dynamodb
.putItem(params)
.promise()
.then(function () {
return document;
});
};
const createItems = function (table, items) {
// Don't touch the original items, work on a copy
const documents = items.slice(0);
if (!documents || documents.length === 0) {
return Promise.resolve();
}
const maxWriteItems = 25; // Currently 25 on AWS
// For fibonacci exponential backoff
let previous = 1;
let anteprevious = 1;
let delay = 0;
// For reverting the back-off
const series = [0];
const writeItems = function (itemsToWrite) {
// Constructs the request
const params = {
RequestItems: {}
};
params.RequestItems[table] = itemsToWrite;
return dynamodb
.batchWriteItem(params)
.promise()
.then(function (batchResponse) {
if (batchResponse.UnprocessedItems[table]) {
// Keep the list of delays
series.push(delay);
delay = previous + anteprevious;
anteprevious = previous;
previous = delay;
console.log(
"%s unprocessed items",
batchResponse.UnprocessedItems[table].length
);
console.log("Delaying next batch, %d seconds", delay);
return Promise.delay(delay * 1000).then(function () {
return writeItems(batchResponse.UnprocessedItems[table]);
});
}
// Revert the back of to the latest position
// Not putting the back off to 0 to keep playing nicely
if (series.length > 1) {
previous = series.pop() || 0;
}
})
.catch(function (err) {
if (err.code === "ProvisionedThroughputExceededException") {
console.log(
"Provisioned Capacity error when creating items, delaying 15 seconds"
);
return Promise.delay(15 * 1000).then(function () {
return writeItems(itemsToWrite);
});
}
console.log(err);
throw err;
});
};
// Returns a promise of the write operation
const writeOperation = function (documentsToWrite) {
const itemsToWrite = [];
documentsToWrite.forEach(function (document) {
// Dop not generate id if already present
if (!document.id) {
document.id = uuidv4();
}
const item = {};
Object.keys(document).forEach(function (key) {
item[key] = utils.itemize(document[key]);
});
itemsToWrite.push({
PutRequest: {
Item: item
}
});
});
return writeItems(itemsToWrite);
};
// Contains arrays of $maxWriteItems items to save
const chunkedDocuments = [];
while (documents.length) {
chunkedDocuments.push(documents.splice(0, maxWriteItems));
}
// Wait for all promises to be fulfilled one by one
return Promise.each(chunkedDocuments, writeOperation);
};
const removeItems = function (table, items, keys) {
// Don't touch the original items, work on a copy
const documents = items.slice(0);
if (!documents || documents.length === 0) {
return Promise.resolve();
}
// By default id will be the key
if (!keys) {
keys = ["id"];
}
const maxWriteItems = 25; // Currently 25 on AWS
// For fibonacci exponential backoff
let previous = 1;
let anteprevious = 1;
let delay = 0;
// For reverting the back-off
const series = [0];
const deleteItems = function (PutRequests) {
// Constructs the request
const params = {
RequestItems: {}
};
params.RequestItems[table] = PutRequests;
return dynamodb
.batchWriteItem(params)
.promise()
.then(function (batchResponse) {
if (batchResponse.UnprocessedItems[table]) {
// Keep the list of delays
series.push(delay);
delay = previous + anteprevious;
anteprevious = previous;
previous = delay;
console.log(
"%s unprocessed items",
batchResponse.UnprocessedItems[table].length
);
console.log("Delaying next batch, %d seconds", delay);
return Promise.delay(delay * 1000).then(function () {
return deleteItems(batchResponse.UnprocessedItems[table]);
});
}
// Revert the back of to the latest position
// Not putting the back off to 0 to keep playing nicely
if (series.length > 1) {
previous = series.pop() || 0;
}
})
.catch(function (err) {
if (err.code === "ProvisionedThroughputExceededException") {
console.log(
"Provisioned Capacity error when deleting, delaying 15 seconds"
);
return Promise.delay(15 * 1000).then(function () {
return deleteItems(PutRequests);
});
}
throw err;
});
};
// Returns a promise of the delete operation
const deleteOperation = function (documentsToDelete) {
const itemsToDelete = [];
documentsToDelete.forEach(function (document) {
const item = {};
Object.keys(document).forEach(function (key) {
if (keys.indexOf(key) > -1) {
item[key] = utils.itemize(document[key]);
}
});
itemsToDelete.push({
DeleteRequest: {
Key: item
}
});
});
return deleteItems(itemsToDelete);
};
// Contains arrays of $maxWriteItems items to save
const chunkedDocuments = [];
while (documents.length) {
chunkedDocuments.push(documents.splice(0, maxWriteItems));
}
// Wait for all promises to be fulfilled one by one
return Promise.each(chunkedDocuments, deleteOperation);
};
const update = function (table, document, conditions, keys, itemsToRemove) {
// By default id will be the key
if (!keys) {
keys = ["id"];
}
const ExpressionAttributeNames = {};
const ExpressionAttributeValues = {};
const UpdateExpressions = [];
Object.keys(document).forEach(function (key) {
if (keys.indexOf(key) > -1) {
return;
}
ExpressionAttributeNames["#" + key] = key;
// Look for something like this: [!some_value]
// This will make sure the value is not update if already set
const conditional =
typeof document[key] === "string" && /\[!(.*)\]/g.exec(document[key]);
// Look for something like this: [++]
// This will increment the value
const increment = typeof document[key] === "string" && /\[\+\+\]/g.exec(document[key]);
// Look for something like this: [--]
// This will decrement the value
const decrement = typeof document[key] === "string" && /\[--\]/g.exec(document[key]);
if (conditional) {
const value = isNaN(conditional[1]) ? conditional[1] : +conditional[1];
ExpressionAttributeValues[":" + key] = utils.itemize(value);
UpdateExpressions.push(
"#" + key + " = " + "if_not_exists(#" + key + ", :" + key + ")"
);
} else if (increment) {
ExpressionAttributeValues[":" + key] = utils.itemize(1);
UpdateExpressions.push("#" + key + " = #" + key + " + :" + key);
} else if (decrement) {
ExpressionAttributeValues[":" + key] = utils.itemize(1);
UpdateExpressions.push("#" + key + " = #" + key + " - :" + key);
} else {
ExpressionAttributeValues[":" + key] = utils.itemize(document[key]);
UpdateExpressions.push("#" + key + " = " + ":" + key);
}
});
const Key = {};
keys.forEach(function (key) {
Key[key] = utils.itemize(document[key]);
});
const params = {
ReturnConsumedCapacity: "TOTAL",
ReturnItemCollectionMetrics: "SIZE",
ReturnValues: "ALL_NEW",
Key: Key,
ExpressionAttributeNames: ExpressionAttributeNames,
ExpressionAttributeValues: ExpressionAttributeValues,
UpdateExpression: "SET " + UpdateExpressions.join(", "),
TableName: table
};
if (conditions && conditions.constructor === Object) {
params.ConditionExpression = conditions.ConditionExpression;
// Append condition values to ExpressionAttributeValues
const values = conditions.ExpressionAttributeValues;
Object.keys(values).forEach(function (key) {
params.ExpressionAttributeValues[key] = utils.itemize(values[key]);
});
}
if (itemsToRemove) {
params.UpdateExpression += " REMOVE " + itemsToRemove.join(", ");
}
return dynamodb
.updateItem(params)
.promise()
.then(function (result) {
// Because ReturnValues is set to ALL_NEW, returned result reflects what is now in database.
return utils.deitemize(result.Attributes);
})
.catch(function (err) {
if (err.code === "ProvisionedThroughputExceededException") {
console.log("Provisioned Capacity error when updating, delaying 15 seconds");
return Promise.delay(15 * 1000).then(function () {
return update(table, document, conditions, keys, itemsToRemove);
});
}
throw err;
});
};
const remove = function (table, document) {
const key = {};
Object.keys(document).forEach(function (k) {
key[k] = utils.itemize(document[k]);
});
const params = {
TableName: table,
Key: key
};
return dynamodb.deleteItem(params).promise();
};
return {
list: list,
query: query,
get: get,
getItems: getItems,
create: create,
createItems: createItems,
removeItems: removeItems,
update: update,
remove: remove
};
};