Skip to content

Add Support for Zod Exported JSON Schema #6279

@KevinKWZheng

Description

@KevinKWZheng

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:{...}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions