-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathask-delivery.js
67 lines (59 loc) · 2.12 KB
/
ask-delivery.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
const AWS = require('aws-sdk');
const uuidv4 = require('uuid/v4');
const docClient = new AWS.DynamoDB.DocumentClient();
const stepfunctions = new AWS.StepFunctions();
const TABLE_NAME = process.env.TABLE_NAME;
const DELIVERY_STEP_FUNCTION_ARN = process.env.DELIVERY_STEP_FUNCTION;
const VALIDATION_MESSAGE = `You haven't provided `;
exports.handler = (event, context, cb) => {
let deliveryRequest = JSON.parse(event.body);
let webhookUrl = deliveryRequest.webhookUrl || 'https://3w99bhuswd.execute-api.eu-central-1.amazonaws.com/latest/character';
let pickupTime = deliveryRequest.pickupTime;
let pickupAddress = deliveryRequest.pickupAddress;
let deliveryAddress = deliveryRequest.deliveryAddress;
if (!webhookUrl) cb(formatReply(`${VALIDATION_MESSAGE} a webhookUrl`));
if (!pickupTime) cb(formatReply(`${VALIDATION_MESSAGE} a pickupTime`));
if (!pickupAddress) cb(formatReply(`${VALIDATION_MESSAGE} a pickupAddress`));
if (!deliveryAddress) cb(formatReply(`${VALIDATION_MESSAGE} a deliveryAddress`));
let deliveryId = uuidv4();
docClient.put({
TableName: TABLE_NAME,
Item: {
deliveryId: deliveryId,
webhookUrl: webhookUrl,
pickupTime: pickupTime,
pickupAddress: pickupAddress,
deliveryAddress: deliveryAddress,
deliveryStatus: 'REQUESTED'
}
}).promise().then(response => {
let params = {
stateMachineArn: DELIVERY_STEP_FUNCTION_ARN,
input: `{"deliveryId": "${deliveryId}", "webhookUrl": "${webhookUrl}", "pickupAddress": "${pickupAddress}" , "deliveryAddress": "${deliveryAddress}"}`
};
//TODO: check for promises
stepfunctions.startExecution(params, function(err, data) {
if (err) {
console.log(err, err.stack);
cb(formatReply(err))
return;
}
console.log(data);
cb(null, formatReply(null, { deliveryId: deliveryId }));
});
}).catch(err => {
console.log(err);
cb(formatReply(err));
});
};
function formatReply(errorMessage, data) {
let statusCode = errorMessage ? 400 : 200;
let bodyData = errorMessage ? {message: errorMessage} : data;
return {
statusCode: statusCode,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bodyData)
};
}