-
Notifications
You must be signed in to change notification settings - Fork 6
/
plugin.js
81 lines (65 loc) · 1.99 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'use strict'
const fp = require('fastify-plugin')
const Knex = require('knex')
const { SUPPORTED_CLIENTS } = require('knex/lib/constants')
const { Model, knexSnakeCaseMappers } = require('objection')
const defaultKnexConfig = {
client: 'better-sqlite3',
useNullAsDefault: true,
connection: {
filename: './default.sqlite'
}
}
function fastifyObjectionjs (fastify, options, next) {
const knexConfig = Object.assign(
{},
defaultKnexConfig,
options.knexConfig,
knexSnakeCaseMappers({
upperCase: options.upperCase || false,
underscoreBeforeDigits: options.underscoreBeforeDigits || false,
underscoreBetweenUppercaseLetters: options.underscoreBetweenUppercaseLetters || false
})
)
if (SUPPORTED_CLIENTS.indexOf(knexConfig.client) === -1) {
next(new Error(`unsupported client, 'fastify-objectionjs' only support ${SUPPORTED_CLIENTS.join(', ')}.`))
return
}
const knexConnection = Knex(knexConfig)
const objection = {
knex: knexConnection
}
Model.knex(knexConnection)
if (options.models) {
if (!Array.isArray(options.models) || options.models.length < 1) {
next(new Error('You need to provide a valid array of `objection.js` models.'))
return
}
objection.models = {}
for (let i = 0; i < options.models.length; i += 1) {
const model = options.models[i]
if (model.idColumn && model.tableName && model.QueryBuilder) {
objection.models[model.name.replace(/^\w/, c => c.toLowerCase())] = model
}
}
if (Object.keys(objection.models).length < 1) {
next(new Error('The supplied models are invalid.'))
return
}
}
if (!fastify.objection) {
fastify.decorate('objection', objection)
} else {
next(new Error('fastify-objectionjs has already registered.'))
return
}
fastify.addHook('onClose', (fastify, done) => {
knexConnection.destroy()
done()
})
next()
}
module.exports = fp(fastifyObjectionjs, {
fastify: '>=4.0.0',
name: 'fastify-objectionjs'
})