-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler_response.js
81 lines (70 loc) · 2.29 KB
/
handler_response.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
'use strict';
const uuid = require('uuid');
const AWS = require('aws-sdk');
AWS.config.setPromisesDependency(require('bluebird'));
const dynamoDb = new AWS.DynamoDB.DocumentClient();
/* POST /responses/accept */
module.exports.submitResponse = async (event) => {
const requestBody = JSON.parse(event.body);
const {
fullName,
attendingCeremony,
attendingBanquet,
dietaryRestrictions,
guests
} = requestBody;
if (typeof fullName !== 'string' ||
typeof attendingCeremony !== 'boolean' ||
typeof attendingBanquet !== 'boolean' ||
typeof dietaryRestrictions !== 'string' ||
Array.isArray(guests) === false) {
return buildResponse(400, 'Validation failed. Invalid input type(s)')
}
const response = buildResponseItem(fullName, attendingCeremony, attendingBanquet, dietaryRestrictions, guests);
await putResponse(response);
return buildResponse(200, response)
}
/* Puts response in dynamo table */
const putResponse = async function putResponseInDynamo(response) {
const responseItem = {
TableName: process.env.RESPONSES_TABLE,
Item: response,
}
await dynamoDb.put(responseItem).promise();
return response;
}
/* Creates response item */
const buildResponseItem = function buildResponseItemDynamoModel(fullName, attendingCeremony, attendingBanquet, dietaryRestrictions, guests) {
let timestamp = new Date().toLocaleString();
return {
id: uuid.v1(),
'fullName': fullName,
'attendingCeremony': attendingCeremony,
'attendingBanquet': attendingBanquet,
'dietaryRestrictions': dietaryRestrictions,
'guests': guests,
'timestamp': timestamp,
};
}
/* GET /responses */
module.exports.listResponses = async (event) => {
let params = {
TableName: process.env.RESPONSES_TABLE,
ExpressionAttributeNames: {"#t": "timestamp"},
ProjectionExpression: 'id, fullName, attendingCeremony, attendingBanquet, dietaryRestrictions, guests, #t'
};
const data = await dynamoDb.scan(params).promise();
return buildResponse(200, data.Items)
}
const buildResponse = function buildHttpResponse(statusCode, message) {
return {
statusCode: statusCode,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
},
body: JSON.stringify({
message: message
})
}
}