简体   繁体   中英

Fastify with TypeScript, How to validate and type a routes request?

My basic server, imports and registers the route join and adds the TypeProvider to fastify.

import Fastify from "fastify";
import { join } from "./routes/onboarding/join";
import { JsonSchemaToTsProvider } from "@fastify/type-provider-json-schema-to-ts";

const fastify = Fastify({
  logger: true,
}).withTypeProvider<JsonSchemaToTsProvider>();

fastify.register(join);

const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();

join route...

import {
  FastifyInstance,
  FastifyReply,
  FastifyRequest,
} from "fastify";

export async function join(fastify: FastifyInstance, _options: Object) {
  fastify.post(
    "/animals",
    {
      schema: {
        body: {
          type: "object",
          required: ["animal"],
          properties: {
            animal: { type: "string" },
          },
        },
      } as const,
    },
    async (request: FastifyRequest, _reply: FastifyReply) => {
      const { animal } = request.body;  <=== errors here on animal
      return animal;
    }
  );
}

The error I get with a red squiggle on const { animal }

Property 'animal' does not exist on type 'unknown'.ts(2339)

The docs are here but I guess they are not that clear

The @fastify/type-provider-json-schema-to-ts Type Provider exports a plugin type FastifyPluginAsyncJsonSchemaToTs that helps TypeScript determine types from the schema definition.

In your example, declare join as that type and remove the explicit parameter types from the plugin function and the handler:

import { FastifyPluginAsyncJsonSchemaToTs } from "@fastify/type-provider-json-schema-to-ts";

export const join: FastifyPluginAsyncJsonSchemaToTs = async function (
  fastify,
  _options
) {
  fastify.post(
    "/animals",
    {
      schema: {
        body: {
          type: "object",
          required: ["animal"],
          properties: {
            animal: { type: "string" },
          },
        },
      } as const,
    },
    async (request, _reply) => {
      const { animal } = request.body; // animal is string
      return animal;
    }
  );
};

Now, animal has type string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM