簡體   English   中英

使用 TypeScript 進行 Fastify,如何驗證和鍵入路由請求?

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

我的基本服務器,導入並注冊路由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();

加入路線...

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;
    }
  );
}

我在const { animal }上用紅色波浪線得到的錯誤

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

文檔在這里,但我想他們不是那么清楚

@fastify/type-provider-json-schema-to-ts類型提供程序導出一個插件類型FastifyPluginAsyncJsonSchemaToTs ,它幫助 TypeScript 從模式定義中確定類型。

在您的示例中, join聲明為該類型並從插件 function 和處理程序中刪除顯式參數類型:

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;
    }
  );
};

現在, animal的類型為string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM