输入和输出验证器
tRPC 过程可以为其输入和/或输出定义验证逻辑,并且验证器还用于推断输入和输出的类型。我们为许多流行的验证器提供一流的支持,你可以 集成验证器 我们不直接支持。
¥tRPC procedures may define validation logic for their input and/or output, and validators are also used to infer the types of inputs and outputs. We have first class support for many popular validators, and you can integrate validators which we don't directly support.
输入验证器
¥Input Validators
通过定义输入验证器,tRPC 可以检查过程调用是否正确,如果不正确则返回验证错误。
¥By defining an input validator, tRPC can check that a procedure call is correct and return a validation error if not.
要设置输入验证器,请使用 procedure.input()
方法:
¥To set up an input validator, use the procedure.input()
method:
ts
// Our examples use Zod by default, but usage with other libraries is identicalimport {z } from 'zod';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (z .object ({name :z .string (),}),).query ((opts ) => {constname =opts .input .name ;return {greeting : `Hello ${opts .input .name }`,};}),});
ts
// Our examples use Zod by default, but usage with other libraries is identicalimport {z } from 'zod';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (z .object ({name :z .string (),}),).query ((opts ) => {constname =opts .input .name ;return {greeting : `Hello ${opts .input .name }`,};}),});
输入合并
¥Input Merging
.input()
可以堆叠起来构建更复杂的类型,当你想要对 中间件 中的过程集合使用一些常见输入时,这特别有用。
¥.input()
can be stacked to build more complex types, which is particularly useful when you want to utilise some common input to a collection of procedures in a middleware.
ts
constbaseProcedure =t .procedure .input (z .object ({townName :z .string () })).use ((opts ) => {constinput =opts .input ;console .log (`Handling request with user from: ${input .townName }`);returnopts .next ();});export constappRouter =t .router ({hello :baseProcedure .input (z .object ({name :z .string (),}),).query ((opts ) => {constinput =opts .input ;return {greeting : `Hello ${input .name }, my friend from ${input .townName }`,};}),});
ts
constbaseProcedure =t .procedure .input (z .object ({townName :z .string () })).use ((opts ) => {constinput =opts .input ;console .log (`Handling request with user from: ${input .townName }`);returnopts .next ();});export constappRouter =t .router ({hello :baseProcedure .input (z .object ({name :z .string (),}),).query ((opts ) => {constinput =opts .input ;return {greeting : `Hello ${input .name }, my friend from ${input .townName }`,};}),});
输出验证器
¥Output Validators
验证输出并不总是与定义输入一样重要,因为 tRPC 通过推断过程的返回类型为你提供自动类型安全。定义输出验证器的一些原因包括:
¥Validating outputs is not always as important as defining inputs, since tRPC gives you automatic type-safety by inferring the return type of your procedures. Some reasons to define an output validator include:
检查从不受信任的来源返回的数据是否正确
¥Checking that data returned from untrusted sources is correct
确保你不会向客户端返回不必要的数据
¥Ensure that you are not returning more data to the client than necessary
如果输出验证失败,服务器将响应 INTERNAL_SERVER_ERROR
。
¥If output validation fails, the server will respond with an INTERNAL_SERVER_ERROR
.
ts
import {z } from 'zod';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .output (z .object ({greeting :z .string (),}),).query ((opts ) => {return {gre ,};}),});
ts
import {z } from 'zod';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .output (z .object ({greeting :z .string (),}),).query ((opts ) => {return {gre ,};}),});
最基本的验证器:一个函数
¥The most basic validator: a function
你可以使用函数定义验证器,而无需任何第三方依赖。
¥You can define a validator without any 3rd party dependencies, with a function.
除非你有特定需求,否则我们不建议创建自定义验证器,但重要的是要了解这里没有魔法 - 这只是 TypeScript!
¥We don't recommend making a custom validator unless you have a specific need, but it's important to understand that there's no magic here - it's just typescript!
在大多数情况下,我们建议你使用 验证库
¥In most cases we recommend you use a validation library
ts
import {initTRPC } from '@trpc/server';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input ((value ): string => {if (typeofvalue === 'string') {returnvalue ;}throw newError ('Input is not a string');}).output ((value ): string => {if (typeofvalue === 'string') {returnvalue ;}throw newError ('Output is not a string');}).query ((opts ) => {const {input } =opts ;return `hello ${input }`;}),});export typeAppRouter = typeofappRouter ;
ts
import {initTRPC } from '@trpc/server';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input ((value ): string => {if (typeofvalue === 'string') {returnvalue ;}throw newError ('Input is not a string');}).output ((value ): string => {if (typeofvalue === 'string') {returnvalue ;}throw newError ('Output is not a string');}).query ((opts ) => {const {input } =opts ;return `hello ${input }`;}),});export typeAppRouter = typeofappRouter ;
库集成
¥Library integrations
tRPC 可以与许多流行的验证和解析库一起使用。以下是我们正式维护支持的验证器的一些使用示例。
¥tRPC works out of the box with a number of popular validation and parsing libraries. The below are some examples of usage with validators which we officially maintain support for.
与 Zod
¥With Zod
Zod 是我们的默认推荐,它拥有强大的生态系统,这使其成为在代码库的多个部分中使用的绝佳选择。如果你没有自己的观点,并且想要一个不会限制未来需求的强大库,那么 Zod 是一个不错的选择。
¥Zod is our default recommendation, it has a strong ecosystem which makes it a great choice to use in multiple parts of your codebase. If you have no opinion of your own and want a powerful library which won't limit future needs, Zod is a great choice.
ts
import {initTRPC } from '@trpc/server';import {z } from 'zod';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (z .object ({name :z .string (),}),).output (z .object ({greeting :z .string (),}),).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
ts
import {initTRPC } from '@trpc/server';import {z } from 'zod';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (z .object ({name :z .string (),}),).output (z .object ({greeting :z .string (),}),).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
与 是的
¥With Yup
ts
import {initTRPC } from '@trpc/server';import * asyup from 'yup';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (yup .object ({name :yup .string ().required (),}),).output (yup .object ({greeting :yup .string ().required (),}),).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
ts
import {initTRPC } from '@trpc/server';import * asyup from 'yup';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (yup .object ({name :yup .string ().required (),}),).output (yup .object ({greeting :yup .string ().required (),}),).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
与 Superstruct
¥With Superstruct
ts
import {initTRPC } from '@trpc/server';import {object ,string } from 'superstruct';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (object ({name :string () })).output (object ({greeting :string () })).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
ts
import {initTRPC } from '@trpc/server';import {object ,string } from 'superstruct';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (object ({name :string () })).output (object ({greeting :string () })).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
与 scale-ts
¥With scale-ts
ts
import {initTRPC } from '@trpc/server';import * as$ from 'scale-codec';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input ($ .object ($ .field ('name',$ .str ))).output ($ .object ($ .field ('greeting',$ .str ))).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
ts
import {initTRPC } from '@trpc/server';import * as$ from 'scale-codec';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input ($ .object ($ .field ('name',$ .str ))).output ($ .object ($ .field ('greeting',$ .str ))).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
与 典型的典型
¥With Typia
ts
import { initTRPC } from '@trpc/server';import typia from 'typia';import { v4 } from 'uuid';import { IBbsArticle } from '../structures/IBbsArticle';const t = initTRPC.create();const publicProcedure = t.procedure;export const appRouter = t.router({store: publicProcedure.input(typia.createAssert<IBbsArticle.IStore>()).output(typia.createAssert<IBbsArticle>()).query(({ input }) => {return {id: v4(),writer: input.writer,title: input.title,body: input.body,created_at: new Date().toString(),};}),});export type AppRouter = typeof appRouter;
ts
import { initTRPC } from '@trpc/server';import typia from 'typia';import { v4 } from 'uuid';import { IBbsArticle } from '../structures/IBbsArticle';const t = initTRPC.create();const publicProcedure = t.procedure;export const appRouter = t.router({store: publicProcedure.input(typia.createAssert<IBbsArticle.IStore>()).output(typia.createAssert<IBbsArticle>()).query(({ input }) => {return {id: v4(),writer: input.writer,title: input.title,body: input.body,created_at: new Date().toString(),};}),});export type AppRouter = typeof appRouter;
与 ArkType
¥With ArkType
ts
import {initTRPC } from '@trpc/server';import {type } from 'arktype';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (type ({name : 'string' }).assert ).output (type ({greeting : 'string' }).assert ).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
ts
import {initTRPC } from '@trpc/server';import {type } from 'arktype';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (type ({name : 'string' }).assert ).output (type ({greeting : 'string' }).assert ).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
与 @effect/schema
¥With @effect/schema
ts
import * asS from '@effect/schema/Schema';import {initTRPC } from '@trpc/server';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (S .parseSync (S .struct ({name :S .string }))).output (S .parseSync (S .struct ({greeting :S .string }))).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
ts
import * asS from '@effect/schema/Schema';import {initTRPC } from '@trpc/server';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (S .parseSync (S .struct ({name :S .string }))).output (S .parseSync (S .struct ({greeting :S .string }))).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
与 runtypes
¥With runtypes
ts
import {initTRPC } from '@trpc/server';import * asT from 'runtypes';constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (T .Record ({name :T .String })).output (T .Record ({greeting :T .String })).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
ts
import {initTRPC } from '@trpc/server';import * asT from 'runtypes';constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (T .Record ({name :T .String })).output (T .Record ({greeting :T .String })).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
与 瓦利博特
¥With Valibot
ts
import {wrap } from '@decs/typeschema';import {initTRPC } from '@trpc/server';import {object ,string } from 'valibot';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (wrap (object ({name :string () }))).output (wrap (object ({greeting :string () }))).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
ts
import {wrap } from '@decs/typeschema';import {initTRPC } from '@trpc/server';import {object ,string } from 'valibot';export constt =initTRPC .create ();constpublicProcedure =t .procedure ;export constappRouter =t .router ({hello :publicProcedure .input (wrap (object ({name :string () }))).output (wrap (object ({greeting :string () }))).query (({input }) => {return {greeting : `hello ${input .name }`,};}),});export typeAppRouter = typeofappRouter ;
贡献你自己的验证器库
¥Contributing your own Validator Library
如果你正在开发支持 tRPC 使用的验证器库,请随时为此页面打开 PR,其用法与此处的其他示例相同,以及指向你的文档的链接。
¥If you work on a validator library which supports tRPC usage, please feel free to open a PR for this page with equivalent usage to the other examples here, and a link to your docs.
在大多数情况下,与 tRPC 集成就像满足几个现有类型接口之一一样简单,但在某些情况下,我们可能会接受 PR 来添加新的支持接口。欢迎提出问题进行讨论。你可以在此处检查现有支持的接口:
¥Integration with tRPC in most cases is as simple as meeting one of several existing type interfaces, but in some cases we may accept a PR to add a new supported interface. Feel free to open an issue for discussion. You can check the existing supported interfaces here: