diff --git a/lib/openapiUtil.js b/lib/openapiUtil.js index b9dfce98..b5ef1310 100644 --- a/lib/openapiUtil.js +++ b/lib/openapiUtil.js @@ -3,8 +3,22 @@ const { URL } = require('url') const { localRefResolve } = require('./swaggerUtil') +// TODO: improvement needed, maybe remove the depend of json-schema-resolver +function defToComponent (jsonSchema) { + if (typeof jsonSchema === 'object') { + Object.keys(jsonSchema).forEach(function (key) { + if (key === '$ref') { + jsonSchema[key] = jsonSchema[key].replace('definitions', 'components/schemas') + } else { + jsonSchema[key] = defToComponent(jsonSchema[key]) + } + }) + } + return jsonSchema +} + function plainJsonObjectToOpenapi3 (container, jsonSchema, externalSchemas) { - const obj = localRefResolve(jsonSchema, externalSchemas) + const obj = defToComponent(localRefResolve(jsonSchema, externalSchemas)) let toSwaggerProp switch (container) { case 'cookie': @@ -54,7 +68,7 @@ function plainJsonObjectToOpenapi3 (container, jsonSchema, externalSchemas) { } function getBodyParams (parameters, body, consumes, ref) { - const bodyResolved = ref.resolve(body) + const bodyResolved = defToComponent(ref.resolve(body)) if ((Array.isArray(consumes) && consumes.length === 0) || typeof consumes === 'undefined') { consumes = ['application/json'] @@ -68,7 +82,7 @@ function getBodyParams (parameters, body, consumes, ref) { } function getCommonParams (container, parameters, schema, ref, sharedSchema) { - const resolved = ref.resolve(schema) + const resolved = defToComponent(ref.resolve(schema)) const add = plainJsonObjectToOpenapi3(container, resolved, sharedSchema) add.forEach(openapiSchema => parameters.push(openapiSchema)) } @@ -83,7 +97,7 @@ function generateResponse (fastifyResponseJson, produces, ref) { Object.keys(fastifyResponseJson).forEach(key => { const rawJsonSchema = fastifyResponseJson[key] - const resolved = ref.resolve(rawJsonSchema) + const resolved = defToComponent(ref.resolve(rawJsonSchema)) const content = {} diff --git a/test/openapi.js b/test/openapi.js index d4125833..7e162ee8 100644 --- a/test/openapi.js +++ b/test/openapi.js @@ -776,3 +776,30 @@ test('route with multiple method', t => { }) }) }) + +test('openapi $ref', t => { + t.plan(3) + const fastify = Fastify() + + fastify.register(fastifySwagger, swaggerInfo) + fastify.register(function (instance, _, done) { + instance.addSchema({ $id: 'Order', type: 'object', properties: { id: { type: 'integer' } } }) + instance.post('/', { schema: { body: { $ref: 'Order#' }, response: { 200: { $ref: 'Order#' } } } }, () => {}) + done() + }) + + fastify.ready(err => { + t.error(err) + + const swaggerObject = fastify.swagger() + t.is(typeof swaggerObject, 'object') + + Swagger.validate(swaggerObject) + .then(function (api) { + t.pass('valid swagger object') + }) + .catch(function (err) { + t.fail(err) + }) + }) +})