Created
June 5, 2020 17:05
-
-
Save maxinuss/cea0793ef582235014bfbe1f23f57c27 to your computer and use it in GitHub Desktop.
Pager.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const routes = [ | |
{ | |
method: 'GET', | |
path: '/locations', | |
handler: async (request, h) => { | |
const db = server.app.db; | |
const locationCollection = db.collection('locations'); | |
// query all locations | |
const documents = await locationCollection.find({}).toArray(); | |
return documents; | |
} | |
}, | |
{ | |
method: 'GET', | |
path: '/locations/{locationId}/items', | |
handler: async (request, h) => { | |
const db = server.app.db; | |
const itemCollection = db.collection('items'); | |
const locationCollection = db.collection('locations'); | |
const locationId = parseInt(request.params.locationId); | |
const location = await locationCollection.find({ locationId: locationId}).toArray(); | |
console.log('Location', location); | |
if (location.length === 0) { | |
return h.response().code(404); | |
} | |
// query all locations | |
const items = await itemCollection.find({ locationId: locationId }).toArray(); | |
return items; | |
} | |
}, | |
{ | |
method: 'POST', | |
path: '/locations/{locationId}/order', | |
handler: async (request, h) => { | |
const db = server.app.db; | |
const ordersCollection = db.collection('orders'); | |
const itemCollection = db.collection('items'); | |
let payload = request.payload; | |
let itemIds = []; | |
let itemQuantity = {}; | |
for (let item of payload.items) { | |
itemIds.push(item.itemId); | |
itemQuantity[item.itemId] = item.quantity; | |
} | |
const items = await itemCollection.find({ itemId : { $in: itemIds} }).toArray(); | |
let total = 0; | |
for (let i of items) { | |
total += parseFloat(i.price) * itemQuantity[i.itemId]; | |
} | |
payload = {...payload, total}; | |
const order = await ordersCollection.insertOne(payload); | |
return h.response(order.ops[0]).code(201); | |
} | |
} | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment