-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrud.js
62 lines (50 loc) · 1.23 KB
/
crud.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
'use strict'
const createError = require('@fastify/error')
const MissingControllerError = createError(
'ERR_MISSING_CRUD_CONTROLLER',
'Missing CRUD controller for %s'
)
function crud (fastify, opts, next) {
const { controller } = opts
if (!controller) return next(new MissingControllerError(opts.prefix || '/'))
const config = {
...opts,
list: { url: '/', ...opts.list },
create: { url: '/', ...opts.create },
view: { url: '/:id', ...opts.view },
update: { url: '/:id', ...opts.update },
delete: { url: '/:id', ...opts.delete }
}
if (controller.list) {
fastify.get(config.list.url, {
handler: controller.list,
...config.list
})
}
if (controller.create) {
fastify.post(config.create.url, {
handler: controller.create,
...config.create
})
}
if (controller.view) {
fastify.get(config.view.url, {
handler: controller.view,
...config.view
})
}
if (controller.update) {
fastify.patch(config.update.url, {
handler: controller.update,
...config.update
})
}
if (controller.delete) {
fastify.delete(config.delete.url, {
handler: controller.delete,
...config.delete
})
}
next()
}
module.exports = crud