Skip to content

Commit

Permalink
feat: allow optional response status code validation (#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
sceccotti89 authored Aug 7, 2023
1 parent 30d8c13 commit 1af196c
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 6 deletions.
19 changes: 13 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,16 @@ function fastifyResponseValidation (fastify, opts, next) {
fastify.addHook('onRoute', onRoute)
}

function onRoute (opts) {
if (opts.responseValidation === false) return
if (opts.schema && opts.schema.response) {
opts.preSerialization = opts.preSerialization || []
opts.preSerialization.push(buildHook(opts.schema.response))
function onRoute (routeOpts) {
if (routeOpts.responseValidation === false) return
if (routeOpts.schema && routeOpts.schema.response) {
const responseStatusCodeValidation = routeOpts.responseStatusCodeValidation || opts.responseStatusCodeValidation || false
routeOpts.preSerialization = routeOpts.preSerialization || []
routeOpts.preSerialization.push(buildHook(routeOpts.schema.response, responseStatusCodeValidation))
}
}

function buildHook (schema) {
function buildHook (schema, responseStatusCodeValidation) {
const statusCodes = {}
for (const statusCode in schema) {
const responseSchema = schema[statusCode]
Expand All @@ -67,6 +68,11 @@ function fastifyResponseValidation (fastify, opts, next) {
function preSerialization (req, reply, payload, next) {
let validate = statusCodes[reply.statusCode] || statusCodes[(reply.statusCode + '')[0] + 'xx']

if (responseStatusCodeValidation && validate === undefined) {
next(new Error(`No schema defined for status code ${reply.statusCode}`))
return
}

if (validate !== undefined) {
// Per media type validation
if (validate.constructor === Object) {
Expand All @@ -86,6 +92,7 @@ function fastifyResponseValidation (fastify, opts, next) {
return next(err)
}
}

next()
}
}
Expand Down
71 changes: 71 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,74 @@ test('Disable response validation for every route', async t => {
t.equal(response.statusCode, 200)
t.strictSame(JSON.parse(response.payload), { answer: 42 })
})

test('Enable response status code validation for a specific route', async t => {
const fastify = Fastify()
await fastify.register(plugin)

fastify.route({
method: 'GET',
url: '/',
responseStatusCodeValidation: true,
schema: {
response: {
204: {
type: 'object',
properties: {
answer: { type: 'number' }
}
}
}
},
handler: async (req, reply) => {
return { answer: 42 }
}
})

const response = await fastify.inject({
method: 'GET',
url: '/'
})

t.equal(response.statusCode, 500)
t.strictSame(JSON.parse(response.payload), {
statusCode: 500,
error: 'Internal Server Error',
message: 'No schema defined for status code 200'
})
})

test('Enable response status code validation for every route', async t => {
const fastify = Fastify()
await fastify.register(plugin, { responseStatusCodeValidation: true })

fastify.route({
method: 'GET',
url: '/',
schema: {
response: {
204: {
type: 'object',
properties: {
answer: { type: 'number' }
}
}
}
},
handler: async (req, reply) => {
return { answer: '42' }
}
})

const response = await fastify.inject({
method: 'GET',
url: '/'
})

t.equal(response.statusCode, 500)
t.strictSame(JSON.parse(response.payload), {
statusCode: 500,
error: 'Internal Server Error',
message: 'No schema defined for status code 200'
})
})
2 changes: 2 additions & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Ajv, { Options as AjvOptions } from "ajv";
declare module 'fastify' {
interface RouteShorthandOptions<RawServer extends RawServerBase = RawServerDefault> {
responseValidation?: boolean;
responseStatusCodeValidation?: boolean;
}
}

Expand All @@ -15,6 +16,7 @@ declare namespace fastifyResponseValidation {
plugins?: (Function | [Function, unknown])[];
});
responseValidation?: boolean;
responseStatusCodeValidation?: boolean;
}

export const fastifyResponseValidation: FastifyResponseValidation
Expand Down
2 changes: 2 additions & 0 deletions types/index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ app.register(plugin, {});
app.register(plugin, { ajv: { coerceTypes: true } });
app.register(plugin, { responseValidation: true });
app.register(plugin, { responseValidation: false });
app.register(plugin, { responseStatusCodeValidation: true });
app.register(plugin, { responseStatusCodeValidation: false });
app.register(plugin, { ajv: { plugins: [require('ajv-formats')] } })
app.register(plugin, { ajv: { plugins: [require('ajv-errors')] } })
app.register(plugin, { ajv: { plugins: [[require('ajv-errors'), {}]] } })
Expand Down

0 comments on commit 1af196c

Please sign in to comment.