Help - Configure setValidatorCompiler in Typescript
Opened this issue · 5 comments
💬 Question here
Following docs, I'm trying to setValidatorCompiler like
const schemaCompilers: Record<string, Ajv.Ajv> = {
body: new Ajv({
removeAdditional: 'all',
useDefaults: true,
coerceTypes: false,
addUsedSchema: false,
allErrors: false,
}),
others: new Ajv({
removeAdditional: 'all',
useDefaults: true,
coerceTypes: 'array',
addUsedSchema: false,
allErrors: false,
}),
};
server.setValidatorCompiler((req) => {
if (!req.httpPart) {
throw new Error('Missing httpPart');
}
const compiler = schemaCompilers[req.httpPart] || schemaCompilers['others'];
if (!compiler) {
throw new Error(`Missing compiler for ${req.httpPart}`);
}
return compiler.compile(req.schema);
});
But I'm getting the below typescript error
Argument of type '(req: FastifyRouteSchemaDef<FastifySchema>) => ValidateFunction' is not assignable to parameter of type 'FastifySchemaCompiler<FastifySchema>'.
Call signature return types 'ValidateFunction' and 'FastifyValidationResult' are incompatible.
The types of 'errors' are incompatible between these types.
Type 'ErrorObject[] | null | undefined' is not assignable to type 'FastifySchemaValidationError[] | null | undefined'.
Type 'ErrorObject[]' is not assignable to type 'FastifySchemaValidationError[]'.
Property 'instancePath' is missing in type 'ErrorObject' but required in type 'FastifySchemaValidationError'.
How do I setup different compilers for schema validation?
PS: I don't want to coerce the body json, which is why I'm trying to setup different compilers.
Your Environment
- node version: v22.10.0
- fastify version: 5.0.0
- typescript: 5.6.3
- os: Mac
Thanks for reporting!
Can you provide steps to reproduce? We often need a reproducible example, e.g. some code that allows someone else to recreate your problem by just copying and pasting it. If it involves more than a couple of different file, create a new repository on GitHub and add a link to that.
@mcollina I couldn't reproduce it with a minimal example. I just found that it happens when I use Fastify on the nx mono repo. I'll try to share a reproducible repo.
@mcollina I found the problem to be with the ajv version. For some reason, Eslint is using ajv 6, which conflicts with Fastify ajv 8. I don't know how dependencies are resolved. Due to this typescript is having a tough time picking the correct type.
I'm not sure how to solve this too 😕