-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_user_vehicles.js
76 lines (67 loc) · 2.23 KB
/
get_user_vehicles.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
const aws = require('aws-sdk');
let UsersTableName = process.env.dynamodb_users_table_name;
let VehiclesTableName = process.env.dynamodb_vehicles_table_name;
function stagingOverwrite() {
UsersTableName = `Dev_${process.env.dynamodb_users_table_name}`;
VehiclesTableName = `Dev_${process.env.dynamodb_vehicles_table_name}`;
}
const dynamoDB = new aws.DynamoDB.DocumentClient();
function mapVehicleKeys(vehicleIds) {
return vehicleIds.map((vehicleId) => ({
vehicle_id: vehicleId
}));
}
async function getUser(userId) {
const params = {
TableName: UsersTableName,
Key: {
user_id: userId
},
ProjectionExpression: 'user_id, first_name, last_name, phone, user_identifications, vehicles'
};
const data = await dynamoDB.get(params).promise();
return data.Item;
}
async function getVehicleByIds(vehiclesIds) {
const params = {
RequestItems: {
[VehiclesTableName]: {
Keys: mapVehicleKeys(vehiclesIds),
ProjectionExpression:
'vehicle_id, alias, vehicle_attributes, vehicle_identifications'
}
}
};
const data = await dynamoDB.batchGet(params).promise();
return data.Responses[VehiclesTableName];
}
exports.handler = async (event) => { // eslint-disable-line no-unused-vars
if (event.requestContext.stage === 'staging') { stagingOverwrite(); }
const userId = event.requestContext.authorizer.user_id;
const user = await getUser(userId);
if (user.vehicles.length === 0) {
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({ vehicles: [] })
};
}
const vehiclesRaw = await getVehicleByIds(user.vehicles);
const vehicles = vehiclesRaw.map((v) => ({
vehicle_id: v.vehicle_id,
alias: v.alias,
nickname: v.alias,
nickname_deprecation: 'Use alias instead',
type: v.vehicle_attributes.type,
type_deprecation: 'Use vehicle_attributes.type instead',
seats: v.vehicle_attributes.seats,
seats_deprecation: 'Use vehicle_attributes.seats instead',
vehicle_attributes: v.vehicle_attributes,
vehicle_identifications: v.vehicle_identifications
}));
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({ vehicles })
};
};