'How to configure fastify and openapiglue to only coerce query parameters
Our application is using fastify and we're registering the openapiGlue plugin to parse/validate http requests. We're using the ajv option to disable all type coercion. Everything works great...
However, the issue with the ajv coerce option is that it is applied globally. What we'd like to do is enable type coercion only for the query parameters, but since the ajv coerce option is global, there's no way to do that.
We've tried to register another plugin, that we wrote, after the openapiGlue that uses the fastify setValidatorCompiler() to solve this problem for us. We've set up separate ajv options sections that get applied based on the part of the http request getting validated. The issue is the setValidatorCompiler callback function never gets invoked for any of the message parts, and thus we are unable to enable type coercion on just the query parameters.
It's as if the openapiGlue plugin doesn't want to relinquish control of the message parsing and validating.
Anyone have any suggestions?
// this works
await app.register(openapiGlue, {
specification: localSystemApi,
service: handlers,
prefix: apiPrefix,
ajvOptions: {
coerceTypes: false // defaults to true by openapiGlue otherwise
}
});
// new code to add plugin to only coerce query parameters
// has no effect.
await app.register(ajvPlugin);
// Our ajvPlugin
const httpPartSchema = z.union([z.literal('body'), z.literal('headers'), z.literal('querystring'), z.literal('params')]);
export const ajvPlugin: FastifyPluginAsync<FastifyOpenapiGlueOptions> = async (fastify) => {
fastify.setValidatorCompiler(({ schema, httpPart }) => {
// this code never gets invoked
if (httpPart === undefined) {
throw new Error('Missing httpPart');
}
const parseResult = httpPartSchema.parse(httpPart);
const compiler = schemaCompilers[parseResult];
return compiler.compile(schema) as any;
});
};
Solution 1:[1]
The issue is the setValidatorCompiler callback function never gets invoked for any of the message parts, and thus we are unable to enable type coercion on just the query parameters
This is a feature ?
Fastify does not create any ajv instances if your routes do not use the schema option to speed up your server startup time.
You can do what you need by adding a route that adds a schema.query object.
I would suggest to use the fastify-split-validator plugin to change the ajv settings based on the HTTP entity.
As further reading, this issue in the fastify repository explains in detail how it works.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manuel Spigolon |
