Created
July 27, 2020 14:32
-
-
Save dhm116/24b98513ede16037ca306bd781b236de to your computer and use it in GitHub Desktop.
This file contains 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 locationId = parseInt(request.params.locationId, 10); | |
const db = server.app.db; | |
const itemCollection = db.collection('items'); | |
const items = await itemCollection | |
.find({ locationId }) | |
.toArray(); | |
if (!items.lenth) { | |
const locationCollection = await db.collection('locations'); | |
const location = await locationCollection.findOne({locationId}); | |
if (!location) { | |
return h.response('Not Found').code(404); | |
} | |
} | |
return items; | |
}, | |
}, | |
{ | |
method: 'POST', | |
path: '/locations/{locationId}/order', | |
handler: async (request, h) => { | |
const order = request.payload; | |
const db = server.app.db; | |
const itemCollection = db.collection('items'); | |
const itemIds = order.items.map(item => item.itemId); | |
const prices = await itemCollection | |
.find({ itemId: { $in: itemIds } }) | |
.project({itemId: 1, price: 1}) | |
.toArray(); | |
// Transform [{ itemId, price }, ...] into { itemId: price, ...} | |
const priceLookup = prices.reduce((result, { itemId, price }) => { | |
result[itemId] = price; | |
return result; | |
}, {}); | |
order.total = order.items.reduce((result, orderItem) => { | |
// result += qty * price | |
result += orderItem.quantity * priceLookup[orderItem.itemId]; | |
return result; | |
}, 0); | |
const orderCollection = db.collection('orders'); | |
const result = await orderCollection.insertOne(order); | |
if (result.insertedCount) { | |
order._id = result.insertedId; | |
return h.response(order).code(201); | |
} | |
return h.response('Error').code(400); | |
}, | |
} | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment