-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
48 lines (44 loc) · 1.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
const promiseTwoCallback = (promise, callback) => {
promise
.then(res => callback(res, null))
.catch(err => callback(null, err));
}
const batchWriteAll = (dynamodb, params, callback) => {
const batchSize = 15;
let rawItems = []
Object.entries(params.RequestItems).forEach(([t, tv]) => {
tv.forEach(o => {
const operation = Object.keys(o)[0];
const itemKey = operation === 'DeleteRequest' ? 'Key' : 'Item'
rawItems.push({
TableName: t,
operation,
[itemKey]: o[operation][itemKey]
})
})
})
const batchesArray = rawItems.reduce((acc, curr, i) => {
if (!(i % batchSize)) {
acc.push(rawItems.slice(i, i + batchSize));
}
return acc;
}, []);
const promises = Promise.all(batchesArray.map(b => {
let currentParams = {};
b.forEach(i => {
const itemKey = i.operation === 'DeleteRequest' ? 'Key' : 'Item'
if (!currentParams[i.TableName]) currentParams[i.TableName] = [];
currentParams[i.TableName].push({[i.operation]: {[itemKey]: i[itemKey]}});
});
if( typeof dynamodb.batchWriteItem !== 'undefined') {
return dynamodb.batchWriteItem({RequestItems: currentParams}).promise();
}else if( typeof dynamodb.batchWrite !== 'undefined') {
return dynamodb.batchWrite({RequestItems: currentParams}).promise();
}else{
throw new Error('The first argument passed to `batchWriteAll` should be an instance of dynamoDb or dynamoDB document client.');
}
}));
if (!!callback) return promiseTwoCallback(promises, callback)
return {promise: () => promises};
}
module.exports = {batchWriteAll};