Skip to content

Instantly share code, notes, and snippets.

@weienwong
Created July 28, 2020 21:17
Show Gist options
  • Save weienwong/395bc9c059ffb8610445d30b21670428 to your computer and use it in GitHub Desktop.
Save weienwong/395bc9c059ffb8610445d30b21670428 to your computer and use it in GitHub Desktop.
Wei-En's Pager Code Submission
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/{id}/items',
handler: async (request, h) => {
const locationId = request.params.id
const db = server.app.db;
const locationsCollection = db.collection('locations');
const locations =
await locationsCollection
.find(
{
locationId: Number(locationId)
}
)
.toArray();
if (locations.length === 0) {
return h.response().code(404);
}
const itemsCollection = db.collection('items');
// find single location
const items =
await itemsCollection
.find(
{
locationId: Number(locationId)
}
)
.toArray();
return items;
}
},
{
method: 'POST',
path: '/locations/{id}/order',
handler: async (request, h) => {
const locationId = request.params.id
const db = server.app.db;
const locationsCollection = db.collection('locations');
const locations =
await locationsCollection
.find(
{
locationId: Number(locationId)
}
)
.toArray();
if (locations.length === 0) {
return h.response().code(404);
}
// calculate the total
let total = 0;
for (const i of request.payload.items) {
const item =
await db.collection('items')
.findOne(
{
itemId: i.itemId
}
);
total = total + (i.quantity * item.price);
}
const ordersCollection = db.collection('orders');
const order =
await ordersCollection
.insertOne(request.payload);
const returnedOrder = order.ops[0];
returnedOrder.total = total;
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