-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.js
49 lines (42 loc) · 1.11 KB
/
plugin.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
const fastifyPlugin = require('fastify-plugin');
function fastifyObjectionJsClasses(fastify, options, next) {
if (
!options.classes ||
!Array.isArray(options.classes) ||
options.classes.length < 1
) {
next(
new Error('You need to provide a valid array of `objection.js` classes.')
);
return;
}
const injectableClasses = pick(require('objection'), options.classes);
if (injectableClasses.error) {
next(new Error(injectableClasses.message));
return;
}
if (!fastify.objectionjs) {
fastify.decorate('objectionjs', injectableClasses);
} else {
next(new Error('fastify-objectionjs-classes has already registered.'));
return;
}
next();
}
function pick(object, keys) {
return keys.reduce((obj, key) => {
if (object && object.hasOwnProperty(key)) {
obj[key] = object[key];
} else {
return {
error: true,
message: `${key} is not a valid 'objection.js' class.`,
};
}
return obj;
}, {});
}
module.exports = fastifyPlugin(fastifyObjectionJsClasses, {
fastify: '>=2.0.0',
name: 'fastify-objectionjs-classes',
});