Skip to content

Commit 64c617c

Browse files
authored
fix: reduce the numbers of onReady hooks (#932)
1 parent f3c6940 commit 64c617c

1 file changed

Lines changed: 13 additions & 12 deletions

File tree

lib/util/add-hook.js

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const cloner = require('rfdc')({ proto: true, circles: false })
55

66
function addHook (fastify, pluginOptions) {
77
const routes = []
8+
const instances = []
89
const sharedSchemasMap = new Map()
910
let hookRun = false
1011

@@ -37,27 +38,27 @@ function addHook (fastify, pluginOptions) {
3738
})
3839

3940
fastify.addHook('onRegister', async (instance) => {
40-
// we need to wait the ready event to get all the .getSchemas()
41-
// otherwise it will be empty
42-
// TODO: better handle for schemaId
43-
// when schemaId is the same in difference instance
44-
// the latter will lost
45-
instance.addHook('onReady', (done) => {
46-
const allSchemas = instance.getSchemas()
47-
for (const schemaId of Object.keys(allSchemas)) {
48-
sharedSchemasMap.set(schemaId, allSchemas[schemaId])
49-
}
50-
done()
51-
})
41+
instances.push(instance)
5242
})
5343

5444
fastify.addHook('onReady', (done) => {
5545
hookRun = true
46+
for (const instance of instances) {
47+
// TODO: better handle for schemaId
48+
// when schemaId is the same in difference instance
49+
// the latter will lost
50+
const allSchemas = instance.getSchemas()
51+
for (const schemaId of Object.keys(allSchemas)) {
52+
sharedSchemasMap.set(schemaId, allSchemas[schemaId])
53+
}
54+
}
5655
const allSchemas = fastify.getSchemas()
5756
for (const schemaId of Object.keys(allSchemas)) {
5857
// it is the top-level, we do not expect to have duplicate id
5958
sharedSchemasMap.set(schemaId, allSchemas[schemaId])
6059
}
60+
// clear the instances array to avoid memory leak
61+
instances.length = 0
6162
done()
6263
})
6364

0 commit comments

Comments
 (0)