-
Notifications
You must be signed in to change notification settings - Fork 0
/
start_driver_trip.js
87 lines (78 loc) · 2.41 KB
/
start_driver_trip.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
82
83
84
85
86
87
const aws = require('aws-sdk');
const moment = require('moment');
const TripsIndexName = process.env.dynamodb_trips_index_name;
let TripsTableName = process.env.dynamodb_trips_table_name;
function stagingOverwrite() {
TripsTableName = `Dev_${process.env.dynamodb_trips_table_name}`;
}
const dynamoDB = new aws.DynamoDB.DocumentClient();
function isEmpty(obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
async function startTrip(tripId, userId) {
const timestamp = moment().format('YYYY-MM-DDTHH:mm:ss-04:00');
const newStatus = 'in_progress';
const expectedStatus = 'open';
const params = {
TableName: TripsTableName,
Key: {
trip_id: tripId
},
UpdateExpression:
'set trip_status = :new_status, current_point = :zero, updated_at = :now',
ConditionExpression:
'trip_status = :expected_status and driver_id = :self',
ExpressionAttributeValues: {
':zero': 0,
':new_status': newStatus,
':now': timestamp,
':expected_status': expectedStatus,
':self': userId
},
ReturnValues: 'UPDATED_NEW'
};
const data = await dynamoDB.update(params).promise();
return data.Attributes;
}
async function getTripInProgress(userId) {
const params = {
TableName: TripsTableName,
IndexName: TripsIndexName,
KeyConditionExpression: 'driver_id = :userId',
FilterExpression:
'trip_status = :expectedStatus',
ExpressionAttributeValues: {
':userId': userId,
':expectedStatus': 'in_progress'
}
};
const data = await dynamoDB.query(params).promise();
return data.Items[0];
}
exports.handler = async (event) => {
if (event.requestContext.stage === 'staging') { stagingOverwrite(); }
const userId = event.requestContext.authorizer.user_id;
const tripId = event.pathParameters.trip;
const tripInProgress = await getTripInProgress(userId);
if (tripInProgress && !isEmpty(tripInProgress)) {
return {
statusCode: 409,
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({
action: 'start', success: false, resource: 'trip', message: 'Trip in progress conflict'
})
};
}
await startTrip(tripId, userId);
const responseBody = {
action: 'start',
success: true,
resource: 'trip',
resource_id: tripId
};
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify(responseBody)
};
};