forked from inthepocket/fastify-typeorm-plugin
/
index.js
40 lines (32 loc) · 918 Bytes
/
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
'use strict'
const fp = require('fastify-plugin')
const { createConnection } = require('typeorm')
async function typeormConnector (fastify, options) {
const { namespace } = options
delete options.namespace
const connection = options.connection || await createConnection(options)
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'
})