[英]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.