forked from sohamkamani/node-express-mongo-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.js
59 lines (53 loc) · 1.23 KB
/
routes.js
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
const express = require('express')
const Joi = require('@hapi/joi')
const { insertItem, getItems, updateQuantity } = require('./db')
const router = express.Router()
const itemSchema = Joi.object().keys({
name: Joi.string(),
quantity: Joi.number().integer().min(0)
})
router.post('/item', (req, res) => {
const item = req.body
console.log(req.body)
const result = itemSchema.validate(item)
if (result.error) {
console.log(result.error)
res.status(400).end()
return
}
insertItem(item)
.then(() => {
res.status(200).end()
})
.catch((err) => {
console.log(err)
res.status(500).end()
})
})
router.get('/items', (req, res) => {
getItems()
.then((items) => {
items = items.map((item) => ({
id: item._id,
name: item.name,
quantity: item.quantity
}))
res.json(items)
})
.catch((err) => {
console.log(err)
res.status(500).end()
})
})
router.put('/item/:id/quantity/:quantity', (req, res) => {
const { id, quantity } = req.params
updateQuantity(id, parseInt(quantity))
.then(() => {
res.status(200).end()
})
.catch((err) => {
console.log(err)
res.status(500).end()
})
})
module.exports = router