-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the feature has not already been requested
🚀 Feature Proposal
I propose that fastify, in its Schema validation logic, add support for zod
exported JSON Schema (compliant with draft-4
, draft-7
, draft-2020-12
). However, because the exported schema contains a $schema
property that will cause the validator to throw an error, we must use the 3rd party zod type provider to accomodate the use of zod
.
Motivation
Current schema validator will throw error when using zod
JSON Schemas with code similar to this:
export const onGetConversation: RouteOptions = {
method: `GET`,
url: `/...`,
schema: {
headers: z.toJSONSchema(
z.object({
Authorization: z.templateLiteral(["Bearer ", z.jwt()]),
}),
{ target: "draft-4" }
),
},
handler:{...}
}
The error:
FastifyError [Error]: Failed building the validation schema for GET: /conversations/:conversationId, due to error no schema with key or ref "http://json-schema.org/draft-04/schema#"
Which is not exactly caused by malformed JSON Schema, but rather because the returned schema is something like this:
{
'$schema': 'http://json-schema.org/draft-04/schema#',
type: 'object',
properties: {
Authorization: { type: 'string', pattern: '^Bearer [\\s\\S]{0,}$' }
},
required: [ 'Authorization' ],
additionalProperties: false
}
The $schema
property is cause errors when it should not. I propose that we add this support since this schema is still compliant with the published JSON Schemas.
Example
I suggest we add support for this type of code:
export const onGetConversation: RouteOptions = {
method: `GET`,
url: `/...`,
schema: {
headers: z.toJSONSchema(
z.object({
Authorization: z.templateLiteral(["Bearer ", z.jwt()]),
}),
{ target: "draft-4" }
),
},
handler:{...}
}