-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
47 lines (39 loc) · 1.05 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
'use strict'
const fp = require('fastify-plugin')
const { createConnection } = require('typeorm')
async function typeormConnector (fastify, options) {
const { namespace } = options
delete options.namespace
let connection
if (options.connection) {
connection = options.connection
} else if (Object.keys(options).length) {
connection = await createConnection(options)
} else {
connection = await createConnection()
}
if (namespace) {
if (!fastify.orm) {
fastify.decorate('orm', {})
}
if (fastify.orm[namespace]) {
throw new Error(`Typeorm namespace already used: ${namespace}`)
}
fastify.orm[namespace] = connection
fastify.addHook('onClose', async (instance, done) => {
await instance.orm[namespace].close()
done()
})
} else {
fastify
.decorate('orm', connection)
.addHook('onClose', async (instance, done) => {
await instance.orm.close()
done()
})
}
}
module.exports = fp(typeormConnector, {
fastify: '>= 1.0.0',
name: 'fastify-typeorm'
})