-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.js
75 lines (59 loc) · 1.83 KB
/
util.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
import AWS, { DynamoDB } from "aws-sdk"
const { AWS_REGION = "eu-west-1" } = process.env;
AWS.config.update({ region: AWS_REGION });
const allowedDbMethods = [
"batchGet", "batchWrite",
"delete", "get",
"put", "update",
"scan", "query",
];
export const success = buildResponse.bind(null, 200);
export const failure = buildResponse.bind(null, 500);
export function callDb(action, params) {
if (!allowedDbMethods.includes(action)) {
throw new Error(`Action ${action} is not an allowed DB operation.`);
}
const client = new DynamoDB.DocumentClient();
return client[action](params).promise();
}
export function buildResponse(statusCode, body, headers={}) {
return {
statusCode,
headers,
body: JSON.stringify(body)
};
}
// a very crude function to construct the UpdateExpression
// for the ddb.update operation - this would (probably)
// only work (barely) for this specific use-case
// which is building an expression with a combination of
// SET and REMOVE directives
export function makeUpdateExpression(obj) {
const toSet = [];
const toRemove = [];
let UpdateExpression = "";
const ExpressionAttributeValues = {};
for (const [k, v] of Object.entries(obj)) {
if (!v) {
toRemove.push(k);
continue;
}
toSet.push(k);
ExpressionAttributeValues[`:${k}`] = v;
}
const sets = toSet.reduce((acc, curr, idx, arr) => {
if (idx === (arr.length - 1)) {
return `${acc} ${curr} = :${curr} `;
}
return `${acc} ${curr} = :${curr},`;
}, "SET");
const removes = toRemove.reduce((acc, curr, idx, arr) => {
if (idx === (arr.length - 1)) {
return `${acc} ${curr}`;
}
return `${acc} ${curr},`;
}, "REMOVE");
if (toSet.length) UpdateExpression += sets;
if (toRemove.length) UpdateExpression += removes;
return { UpdateExpression, ExpressionAttributeValues };
}