Skip to content

Instantly share code, notes, and snippets.

@DamienGarrido
Created June 18, 2024 10:40
Show Gist options
  • Save DamienGarrido/4bd5163db7983d42f9f5c4cb86228b86 to your computer and use it in GitHub Desktop.
Save DamienGarrido/4bd5163db7983d42f9f5c4cb86228b86 to your computer and use it in GitHub Desktop.
Fastify request/response validations
/* eslint-disable no-console */
const responseValidation = require('@fastify/response-validation');
const Ajv = require('ajv');
const addFormats = require('ajv-formats');
const fastify = require('fastify');
const { S } = require('fluent-json-schema');
(async () => {
const app = fastify();
const ajv = new Ajv();
addFormats(ajv);
app.setValidatorCompiler(({ schema }) => ajv.compile(schema));
await app.register(responseValidation);
app.post('/validate', {
schema: {
body: S.object()
.additionalProperties(false)
.prop('name', S.string())
.prop('age', S.number())
.required(['name', 'age'])
.valueOf(),
response: {
200: S.object()
.additionalProperties(false)
.prop('missing', S.string())
.prop('headers', S.object()
.additionalProperties(true))
.prop('body', S.object()
.additionalProperties(true))
.required(['missing', 'headers', 'body'])
.valueOf(),
},
},
}, async (req, reply) => reply.send({ headers: req.headers, body: req.body }));
const responseHandler = (error, { statusCode, statusMessage, headers, json }) => {
if (error) console.error({ error });
console.log({ statusCode, statusMessage, headers, body: json() });
};
app.inject({ method: 'POST', url: '/validate', payload: { name: 1.5, age: '20' } }, responseHandler);
app.inject({ method: 'POST', url: '/validate', payload: { name: 'John', age: 20 } }, responseHandler);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment