-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
70 lines (63 loc) · 1.66 KB
/
server.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
60
61
62
63
64
65
66
67
68
69
70
const Joi = require('joi')
const restify = require('restify')
const { name, version } = require('./package.json')
const validator = require('../')
const server = restify.createServer({ name, version })
server.use(restify.plugins.acceptParser(server.acceptable))
server.use(restify.plugins.queryParser())
server.use(restify.plugins.bodyParser({ mapParams: false }))
server.use(restify.plugins.gzipResponse())
// you can pass along all the joi options here
server.use(validator())
// additional middleware etc
server.get({
path: '/:id',
validation: {
schema: {
params: Joi.object().keys({
id: Joi.number().min(0).required()
}).required()
}
}
}, (req, res, next) => {
res.send(200, { id: req.params.id })
next()
})
server.post({
path: '/',
validation: {
schema: {
body: Joi.object().keys({
name: Joi.string().required()
}).required()
},
// overrides middleware settings for this route
options: {
joiOptions: {
allowUnknown: false
}
}
}
}, (req, res, next) => {
res.send(201, { id: 1, name: req.body.name })
next()
})
server.put({
path: '/:id',
// Joi.object().keys({}) schemas work too
validation: {
schema: Joi.object().keys({
params: Joi.object().keys({
id: Joi.number().min(0).required()
}).required(),
body: Joi.object().keys({
id: Joi.number().min(0).required(),
name: Joi.string().required()
}).required()
}).assert('params.id', Joi.ref('body.id'))
}
}, (req, res, next) => {
res.send(200, { id: 1, name: req.body.name })
next()
})
server.listen(8080, () => console.log(`${server.name} listening on: ${server.url}`))