diff --git a/index.js b/index.js index 34eb845..5d16af4 100644 --- a/index.js +++ b/index.js @@ -43,6 +43,14 @@ function fastifyResponseValidation (fastify, opts, next) { function onRoute (routeOpts) { if (routeOpts.responseValidation === false) return if (routeOpts.schema && routeOpts.schema.response) { + const schemas = Object.values(fastify.getSchemas()) + + for (const schema of schemas) { + if (!ajv.getSchema(schema.$id)) { + ajv.addSchema(schema) + } + } + const responseStatusCodeValidation = routeOpts.responseStatusCodeValidation || opts.responseStatusCodeValidation || false routeOpts.preSerialization = routeOpts.preSerialization || [] routeOpts.preSerialization.push(buildHook(routeOpts.schema.response, responseStatusCodeValidation)) diff --git a/test/index.test.js b/test/index.test.js index a572994..e533ee8 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -194,6 +194,42 @@ test('Should support media types', async t => { t.assert.deepStrictEqual(JSON.parse(response.payload), { answer: 42 }) }) +test('Should support ref schema', async (t) => { + const fastify = Fastify() + await fastify.register(plugin) + + fastify.addSchema({ + $id: 'answerSchema', + type: 'object', + properties: { + answer: { type: 'number' } + } + }) + + fastify.route({ + method: 'GET', + url: '/', + schema: { + response: { + '2xx': { + $ref: 'answerSchema' + } + } + }, + handler: async (req, reply) => { + return { answer: 42 } + } + }) + + const response = await fastify.inject({ + method: 'GET', + url: '/' + }) + + t.assert.strictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(JSON.parse(response.payload), { answer: 42 }) +}) + test('Should check anyOf Schema', async t => { const fastify = Fastify() await fastify.register(plugin)