-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
106 lines (81 loc) · 2.2 KB
/
api.js
File metadata and controls
106 lines (81 loc) · 2.2 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
const healthpoint = require('healthpoint')
const db = require('./db')
const Orders = require('./models/orders')
const Products = require('./models/products')
const autoCatch = require('./lib/auto-catch')
const { version } = require('./package.json')
const hp = healthpoint({ version }, function (cb) {
db.checkHealth()
.catch(cb)
.then(isHealthy => {
if (isHealthy) return cb(null, { status: 'UP' })
cb(new Error('Database connectivity issue'))
})
})
module.exports = autoCatch({
checkHealth,
getProduct,
listProducts,
createProduct,
editProduct,
deleteProduct,
createOrder,
listOrders
})
async function checkHealth (req, res, next) {
return hp(req, res)
}
async function getProduct (req, res, next) {
const { id } = req.params
const product = await Products.get(id)
if (!product) return next()
res.json(product)
}
async function listProducts (req, res, next) {
const { offset = 0, limit = 25, tag } = req.query
const products = await Products.list({
offset: Number(offset),
limit: Number(limit),
tag
})
res.json(products)
}
async function createProduct (req, res, next) {
if (!req.user) return forbidden(next)
const product = await Products.create(req.body)
res.json(product)
}
async function editProduct (req, res, next) {
if (!req.user) return forbidden(next)
const change = req.body
const product = await Products.edit(req.params.id, change)
res.json(product)
}
async function deleteProduct (req, res, next) {
if (!req.user) return forbidden(next)
await Products.remove(req.params.id)
res.json({ success: true })
}
async function createOrder (req, res, next) {
const fields = req.body
if (req.user) fields.username = req.user.email
const order = await Orders.create(fields)
res.json(order)
}
async function listOrders (req, res, next) {
const { offset = 0, limit = 25, productId, status } = req.query
const opts = {
offset: Number(offset),
limit: Number(limit),
productId,
status
}
if (req.user) opts.username = req.user.email
const orders = await Orders.list(opts)
res.json(orders)
}
function forbidden (next) {
const err = new Error('Forbidden')
err.statusCode = 403
return next(err)
}