Exifers
Exifers

Reputation: 2822

Fastify json-schema-to-ts type provider doesn't work

I'm trying to implement type inference from JSON schema in Fastify.

This example from the documentation doesn't work for me, as request.query remains unknown or sometimes {}.

Here is a direct copy-paste of the documentation on stackblitz. As you can see the Typescript compilation fails.

enter image description here

Any idea ?

Upvotes: 2

Views: 1122

Answers (2)

Senia Merlin
Senia Merlin

Reputation: 11

this solves the issue (:

npm i json-schema-to-ts

Upvotes: 1

lepsch
lepsch

Reputation: 10349

The Querystring type is not defined hence the error. To define it do like the following:

import { JsonSchemaToTsProvider } from '@fastify/type-provider-json-schema-to-ts';

import fastify from 'fastify';

const server = fastify().withTypeProvider<JsonSchemaToTsProvider>();

server.get<{ Querystring: { foo: number, bar: string } }>(
  '/route',
  {
    schema: {
      querystring: {
        type: 'object',
        properties: {
          foo: { type: 'number' },
          bar: { type: 'string' },
        },
        required: ['foo', 'bar'],
      },
    } as const, // don't forget to use const !
  },
  (request, reply) => {
    const { foo, bar } = request.query; // type safe!
  }
);

Or, to keep it DRY install the @sinclair/typebox package and define it beforehand like:

import { JsonSchemaToTsProvider } from '@fastify/type-provider-json-schema-to-ts';

import fastify from 'fastify';
import { Static, Type } from '@sinclair/typebox';

const server = fastify().withTypeProvider<JsonSchemaToTsProvider>();

const getQuerystring = Type.Object({
  foo: Type.Number(),
  bar: Type.String(),
})

type GetQuerystring = Static<typeof getQuerystring>

server.get<{ Querystring: GetQuerystring }>(
  '/route',
  {
    schema: {
      querystring: getQuerystring,
    } as const, // don't forget to use const !
  },
  (request, reply) => {
    const { foo, bar } = request.query; // type safe!
  }
);

Upvotes: 1

Related Questions