-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
121 lines (105 loc) · 2.39 KB
/
api.js
File metadata and controls
121 lines (105 loc) · 2.39 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
const path = require('path')
const Products = require('./products')
const autoCatch = require('./lib/auto-catch')
const Orders = require('./orders')
/**
* Handle the root route
* @param {object} req
* @param {object} res
*/
function handleRoot(req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
}
/**
* List all products
* @param {object} req
* @param {object} res
*/
async function listProducts(req, res) {
// Extract the limit and offset query parameters
const { offset = 0, limit = 25, tag } = req.query
// Pass the limit and offset to the Products service
res.json(await Products.list({
offset: Number(offset),
limit: Number(limit),
tag
}))
}
/**
* Get a single product
* @param {object} req
* @param {object} res
*/
async function getProduct(req, res, next) {
const { id } = req.params
const product = await Products.get(id)
if (!product) {
return next()
}
return res.json(product)
}
/**
* Create a product
* @param {object} req
* @param {object} res
*/
async function createProduct(req, res, next) {
const product = await Products.create(req.body)
res.json(product)
}
/**
* Edit a product
* @param {object} req
* @param {object} res
* @param {function} next
*/
async function editProduct(req, res, next) {
const change = req.body
const product = await Products.edit(req.params.id, change)
res.json(product)
}
/**
* Delete a product
* @param {*} req
* @param {*} res
* @param {*} next
*/
async function deleteProduct(req, res, next) {
const response = await Products.destroy(req.params.id)
res.json(response)
}
async function createOrder(req, res, next) {
const order = await Orders.create(req.body)
res.json(order)
}
async function listOrders(req, res, next) {
const { offset = 0, limit = 25, productId, status } = req.query
const orders = await Orders.list({
offset: Number(offset),
limit: Number(limit),
productId,
status
})
res.json(orders)
}
async function editOrder(req, res, next) {
const change = req.body
const product = await Orders.edit(req.params.id, change)
res.json(product)
}
async function deleteOrder(req, res, next) {
const response = await Orders.destroy(req.params.id)
res.json(response)
}
module.exports = autoCatch({
handleRoot,
listProducts,
getProduct,
createProduct,
editProduct,
deleteProduct,
createOrder,
listOrders,
editOrder,
deleteOrder
});