Last active
July 26, 2024 17:54
-
-
Save BenjaminLindberg/4403f1fe77fed8d437d4d44d7d6490e2 to your computer and use it in GitHub Desktop.
How to use zod with fastify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Firstly you need to set the validator and serializer compiler to the one included in the fastify-type-provider-zod module. (https://fastify.dev/docs/latest/Reference/Validation-and-Serialization/#validation-and-serialization) | |
// This can be done like: | |
import { | |
serializerCompiler, | |
validatorCompiler | |
} from 'fastify-type-provider-zod'; | |
fastify | |
.setValidatorCompiler(validatorCompiler) | |
.setSerializerCompiler(serializerCompiler); | |
//Place this where you create the fastify instance. | |
// Then for all of the routes you want to use a zod schema with, you simply set the schema to an object. And inside of this object is where you create the zod schema for the different request values, and the responses. | |
// This is usually how I do my routes: | |
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'; | |
import { z } from 'zod'; | |
export const Example = { | |
params: z.object({ | |
uid: z.string().uuid() | |
}), | |
querystring: z.object({ | |
email: z.string().email().toLowerCase() | |
}), | |
body: z.object({ | |
termsOfService: z.boolean().default(false) | |
}), | |
response: { | |
// Define your response here: | |
200: z.object({ | |
message: z.string(), | |
data: z.object({ | |
timestamp: z.number(), | |
randomString: z.string(), | |
randomNumber: z.number() | |
}) | |
}) | |
} | |
}; | |
const plugin: FastifyPluginAsyncZod = async (fastify, _opts) => { | |
fastify.route({ | |
url: '/example/:uid', | |
method: 'POST', | |
schema: Example, // Register the schema | |
handler: async (request, _reply) => { | |
const { uid } = request.params; // uid: string, is a valid uuid string | |
const { email } = request.query; // email: string, is a valid email address in lowercase | |
const { termsOfService } = request.body; // termsOfService: boolean, default value is false | |
console.log( | |
`Processing request with uid: ${uid}, email: ${email}, termsOfService: ${termsOfService}` | |
); | |
return { | |
message: 'Example.', | |
data: { | |
timestamp: Date.now(), | |
randomString: (Math.random() + 1).toString(36).substring(7), | |
randomNumber: Math.floor(Math.random() * 100) + 1, | |
otherField: | |
'This field will automatically get removed by the serializer' | |
} | |
}; | |
/* | |
Example of response: | |
{ | |
"message": "Example.", | |
"data": { | |
"timestamp": 1722018622440, | |
"randomString": "e8rqdh", | |
"randomNumber": 50 | |
} | |
} | |
NOTE: otherField was not included in the response schema, thus not present in the response. | |
*/ | |
} | |
}); | |
}; | |
export default plugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment