-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
51 lines (43 loc) · 1.29 KB
/
index.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
const boom = require('boom')
function plugin (fastify, opts, next) {
fastify.get('/', opts, async (req, reply) => {
try {
reply.type('application/json').code(200).send(await opts.Collection.find())
} catch (err) {
throw boom.boomify(err)
}
})
fastify.get('/:id', opts, async (req, reply) => {
try {
reply.type('application/json').code(200).send(await opts.Collection.findById(req.params.id))
} catch (err) {
throw boom.boomify(err)
}
})
fastify.post('/', opts, async (req, reply) => {
try {
reply.type('application/json').code(201).send(await new opts.Collection(req.body).save())
} catch (err) {
throw boom.boomify(err)
}
})
fastify.put('/:id', opts, async (req, reply) => {
try {
reply.type('application/json').code(200).send(await opts.Collection.findOneAndUpdate({ _id: req.params.id }, req.body, { new: true }))
} catch (err) {
throw boom.boomify(err)
}
})
fastify.delete('/:id', opts, async (req, reply) => {
try {
reply.type('application/json').code(204).send(await opts.Collection.deleteOne({ _id: req.params.id }))
} catch (err) {
throw boom.boomify(err)
}
})
opts.additionalRoute.map(route => {
fastify.route(route)
})
next()
}
module.exports = plugin