Skip to content

Help - Configure setValidatorCompiler in Typescript #1065

Open
@itizarsa

Description

@itizarsa

💬 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is neededquestionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions