使用 TypeScript Fastify,如何验证和输入路由请求?

Bil*_*ill 5 typescript fastify

我的基本服务器导入并注册路由join并添加 TypeProvider 以进行 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();
Run Code Online (Sandbox Code Playgroud)

加入路线...

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;
    }
  );
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误是带有红色曲线的const { animal }

Property 'animal' does not exist on type 'unknown'.ts(2339)
Run Code Online (Sandbox Code Playgroud)

文档在这里,但我想它们不太清楚

msm*_*ens 4

类型@fastify/type-provider-json-schema-to-ts提供程序导出一个插件类型FastifyPluginAsyncJsonSchemaToTs,帮助 TypeScript 从架构定义中确定类型。

在您的示例中,声明join为该类型并从插件函数和处理程序中删除显式参数类型:

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;
    }
  );
};
Run Code Online (Sandbox Code Playgroud)

现在,animal有类型string