From e35d2f6b7f075804ff898fa921544c5b7d7744c0 Mon Sep 17 00:00:00 2001 From: Sam Chung Date: Thu, 31 Oct 2024 02:06:47 +1100 Subject: [PATCH] fix: soft fail fallback response description lookups (#832) --- lib/util/resolve-schema-reference.js | 2 +- test/spec/openapi/schema.js | 57 ++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/lib/util/resolve-schema-reference.js b/lib/util/resolve-schema-reference.js index 06bf7757..80189941 100644 --- a/lib/util/resolve-schema-reference.js +++ b/lib/util/resolve-schema-reference.js @@ -10,7 +10,7 @@ function resolveSchemaReference (rawSchema, ref) { return undefined } - return resolvedReference.definitions[schemaId] + return resolvedReference.definitions?.[schemaId] } module.exports = { diff --git a/test/spec/openapi/schema.js b/test/spec/openapi/schema.js index 4d6c9f24..53c463b9 100644 --- a/test/spec/openapi/schema.js +++ b/test/spec/openapi/schema.js @@ -1022,6 +1022,63 @@ test('add default properties for url params when missing schema.params', async t }) }) +test('support custom transforms which returns $ref in the response', async t => { + const customObject = {} + const opt = { + schema: { + response: { + 200: customObject + } + } + } + + const fastify = Fastify() + await fastify.register(fastifySwagger, { + openapi: true, + transform: ({ schema, ...rest }) => { + schema.response['200'] = { + $ref: '#/components/schemas/CustomObject' + } + return { + schema, + ...rest + } + }, + transformObject: ({ openapiObject }) => { + openapiObject.components.schemas.CustomObject = { + type: 'object', + properties: { + hello: { + type: 'string' + } + } + } + return openapiObject + } + }) + fastify.post('/', opt, () => { }) + await fastify.ready() + + const swaggerObject = fastify.swagger() + + const swaggerPath = swaggerObject.paths['/'].post + t.has(swaggerPath.responses['200'].content['application/json'].schema, { + $ref: '#/components/schemas/CustomObject' + }) + + // validate seems to mutate the swaggerPath object + const api = await Swagger.validate(swaggerObject) + const definedPath = api.paths['/'].post + t.same(definedPath.responses['200'].content['application/json'].schema, { + type: 'object', + properties: { + hello: { + type: 'string' + } + } + }) +}) + test('avoid overwriting params when schema.params is provided', async t => { const opt = { schema: {