-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin.js
More file actions
43 lines (32 loc) · 958 Bytes
/
Copy pathplugin.js
File metadata and controls
43 lines (32 loc) · 958 Bytes
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
const fp = require('fastify-plugin');
const knex = require('knex');
const objection = require('objection');
const { ERR_MISSING_REQUIRED, ERR_INVALID_PROPERTY } = require('./errors');
const plugin = (instance, options, next) => {
if (!options.connection || !options.models) {
return next(new Error(ERR_MISSING_REQUIRED));
}
if (!Array.isArray(options.models) || !options.models.length) {
return next(new Error(ERR_INVALID_PROPERTY));
}
const connection = knex({
client: 'pg',
connection: options.connection,
});
const models = {};
objection.Model.knex(connection);
options.models.forEach((model) => {
models[model.name] = model;
});
instance.decorate('models', models);
instance.decorate('knex', connection);
instance.addHook('onClose', (_, done) => {
connection.destroy();
done();
});
return next();
};
module.exports = fp(plugin, {
fastify: '>=2.0.0',
name: 'fastify-objection',
});