Skip to content

Commit

Permalink
feat(start_driver_trip): validate no in progress trip
Browse files Browse the repository at this point in the history
  • Loading branch information
Franco Méndez committed Nov 8, 2019
1 parent 1e2b206 commit 9e3c3c9
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions start_driver_trip.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ const aws = require('aws-sdk');
const moment = require('moment');

const TripsTableName = process.env.dynamodb_trips_table_name;
const TripsIndexName = process.env.dynamodb_trips_index_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';
Expand All @@ -15,11 +20,11 @@ async function startTrip(tripId, userId) {
trip_id: tripId
},
UpdateExpression:
'set trip_status = :new_status, current_point = :val, updated_at = :now',
'set trip_status = :new_status, current_point = :zero, updated_at = :now',
ConditionExpression:
'trip_status = :expected_status and driver_id = :self',
ExpressionAttributeValues: {
':val': 0,
':zero': 0,
':new_status': newStatus,
':now': timestamp,
':expected_status': expectedStatus,
Expand All @@ -31,10 +36,37 @@ async function startTrip(tripId, userId) {
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) => {
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',
Expand Down

0 comments on commit 9e3c3c9

Please sign in to comment.