-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathfunction.js
More file actions
78 lines (65 loc) · 1.71 KB
/
function.js
File metadata and controls
78 lines (65 loc) · 1.71 KB
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
const nosql = require('./nosql');
const nosqlClient = nosql.nosql.get_instance();
const nosqlTableName = "shopping_cart";
async function addProduct(cartId, productId, productName, price, quantity) {
await nosqlClient.insert(
nosqlTableName,
["cart_id", cartId],
["product_id", productId],
{ price: price, quantity: quantity, name: productName }
);
}
async function getProducts(cartId, productId) {
return await nosqlClient.get(
nosqlTableName,
["cart_id", cartId],
["product_id", productId]
);
}
async function queryProducts(cartId) {
const res = await nosqlClient.query(
nosqlTableName,
["cart_id", cartId],
"product_id"
);
const products = [];
let priceSum = 0;
let quantitySum = 0;
for (const product of res) {
products.push(product.name);
priceSum += product.price;
quantitySum += product.quantity;
}
const avgPrice = quantitySum > 0 ? priceSum / quantitySum : 0.0;
return {
products: products,
total_cost: priceSum,
avg_price: avgPrice
};
}
exports.handler = async function(event) {
const results = [];
for (const request of event.requests) {
const route = request.route;
const body = request.body;
let res;
if (route === "PUT /cart") {
await addProduct(
body.cart,
body.product_id,
body.name,
body.price,
body.quantity
);
res = {};
} else if (route === "GET /cart/{id}") {
res = await getProducts(body.cart, request.path.id);
} else if (route === "GET /cart") {
res = await queryProducts(body.cart);
} else {
throw new Error(`Unknown request route: ${route}`);
}
results.push(res);
}
return { result: results };
};