From 6b0b563eb40a990b50167e656bc0d8c046c3205d Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Tue, 19 Sep 2023 13:10:14 +0200 Subject: [PATCH] Fix race condition that have the spec cached if .swagger() is called before .ready() (#757) Signed-off-by: Matteo Collina --- lib/util/add-hook.js | 5 +++++ test/decorator.js | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/util/add-hook.js b/lib/util/add-hook.js index 0f23fb6c..afe6e683 100644 --- a/lib/util/add-hook.js +++ b/lib/util/add-hook.js @@ -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 || {} @@ -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 @@ -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' }, diff --git a/test/decorator.js b/test/decorator.js index edb29805..6c2288be 100644 --- a/test/decorator.js +++ b/test/decorator.js @@ -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)) +})