Skip to content

Commit

Permalink
Fix race condition that have the spec cached if .swagger() is called …
Browse files Browse the repository at this point in the history
…before .ready() (#757)

Signed-off-by: Matteo Collina <[email protected]>
  • Loading branch information
mcollina authored Sep 19, 2023
1 parent caa939c commit 6b0b563
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/util/add-hook.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const cloner = require('rfdc')({ proto: true, circles: false })
function addHook (fastify, pluginOptions) {
const routes = []
const sharedSchemasMap = new Map()
let hookRun = false

fastify.addHook('onRoute', (routeOptions) => {
const routeConfig = routeOptions.config || {}
Expand Down Expand Up @@ -51,6 +52,7 @@ function addHook (fastify, pluginOptions) {
})

fastify.addHook('onReady', (done) => {
hookRun = true
const allSchemas = fastify.getSchemas()
for (const schemaId of Object.keys(allSchemas)) {
// it is the top-level, we do not expect to have duplicate id
Expand All @@ -62,6 +64,9 @@ function addHook (fastify, pluginOptions) {
return {
routes,
Ref () {
if (hookRun === false) {
throw new Error('.swagger() must be called after .ready()')
}
const externalSchemas = cloner(Array.from(sharedSchemasMap.values()))
return Ref(Object.assign(
{ applicationUri: 'todo.com' },
Expand Down
20 changes: 20 additions & 0 deletions test/decorator.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,23 @@ test('fastify.swagger should exist', async (t) => {
await fastify.ready()
t.ok(fastify.swagger)
})

test('fastify.swagger should throw if called before ready', async (t) => {
t.plan(1)
const fastify = Fastify()

await fastify.register(fastifySwagger)

t.throws(fastify.swagger.bind(fastify))
})

test('fastify.swagger should throw if called before ready (openapi)', async (t) => {
t.plan(1)
const fastify = Fastify()

await fastify.register(fastifySwagger, {
openapi: {}
})

t.throws(fastify.swagger.bind(fastify))
})

0 comments on commit 6b0b563

Please sign in to comment.