-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamodb-converter.js
66 lines (54 loc) · 1.38 KB
/
dynamodb-converter.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
const AWS = require('aws-sdk');
const convertObj = require('json-to-dynamo');
const uuidv4 = require('uuid/v4');
let APPEND_UUID = false;
const convertObjectToPutRequest = obj => {
let item = convertObj(obj);
if (APPEND_UUID) {
item = { ...item, uuid: { S: uuidv4() } };
}
return {
PutRequest: {
Item: item
}
};
};
const convertForDynamo = (data, tableName) => {
const result = {
RequestItems: {
[tableName]: data.map(convertObjectToPutRequest)
}
};
return result;
};
const convertArray = (array, tableName, uuid = false) => {
if (!Array.isArray(array)) {
throw new Error('Must provide array');
}
APPEND_UUID = uuid;
const data = convertForDynamo(array, tableName);
return data;
};
const convert = (obj, uuid = false) => {
let marshalled = AWS.DynamoDB.Converter.marshall(obj);
if (uuid) {
marshalled = { ...marshalled, uuid: { S: uuidv4() } };
}
return marshalled;
};
const unconvert = obj => {
return AWS.DynamoDB.Converter.unmarshall(obj);
};
const batch = (array, number = 25) => {
return array.chunk(number);
};
Object.defineProperty(Array.prototype, 'chunk', {
value: function(chunkSize) {
let temporal = [];
for (let i = 0; i < this.length; i += chunkSize) {
temporal.push(this.slice(i, i + chunkSize));
}
return temporal;
}
});
module.exports = { convertArray, convert, unconvert, batch };