-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
37 lines (30 loc) · 1.02 KB
/
index.ts
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
import fp from 'fastify-plugin'
import { MikroORM } from '@mikro-orm/core'
import type { FastifyPluginAsync } from 'fastify'
import type { fastifyMikroOrm } from './types'
const fastifyMikroORM: FastifyPluginAsync<fastifyMikroOrm.MikroORMPluginOptions> = async function (fastify, options) {
if (options.forkOnRequest === undefined) {
options.forkOnRequest = true
}
const orm = await MikroORM.init(options)
const mikroORM = {
orm
}
fastify.decorate('mikroORM', mikroORM)
if (options.forkOnRequest) {
fastify.addHook('onRequest', async function (this: typeof fastify, request, reply) {
request.mikroORM = {
orm: Object.assign({}, this.mikroORM.orm)
}
request.mikroORM.orm.em = request.mikroORM.orm.em.fork()
})
} else {
fastify.addHook('onRequest', async function (this: typeof fastify, request, reply) {
request.mikroORM = this.mikroORM
})
}
fastify.addHook('onClose', () => orm.close())
}
export default fp(fastifyMikroORM, {
name: 'fastify-mikro-orm'
})