6.1-tRPC
Create by fall on 21 Apr 2024 Recently revised in 21 Apr 2024
tRPC
什么是 tRPC,为了解决什么问题?
当请求 API 时,获取不到返回内容的类型(或者是前端也维护一套类型,用来表达返回的每一个接口的类型),从而在 debug 时,经常遇到 Cannot read properties of undefined (reading 'xxx')
问题。
解决了以下几个问题:
- 请求的时候,参数传递错误(类型,变量名称,字段位置)
- 无返回内容的类型提示
- 维护一套关于接口对应的返回值的类型
tRPC 简化客户端与服务端之间的通信过程,并提供高效的类型安全。可以使用类似本地函数调用的方式来调用远程函数,同时自动处理序列化和反序列化、错误处理和通信协议等底层细节。
- Automatic type-safety(自动类型安全)
- Snappy DX(敏捷高效的开发者体验)
- Is framework agnostic (不依赖于特定框架)
- Amazing autocompletion(出色的自动补全功能)
- Light bundle size(轻量级打包大小)
tRPC 只有当您在诸如 Next、Nuxt、SvelteKit、SolidStart 等全栈项目中使用 TypeScript 时,tRPC 才会发挥其优势。
使用
定义服务端
这里以 Next.js 的目录结构而定。创建 server/trpc.ts
,如下代码。分别导出 router, middleware, procedure
import { initTRPC } from '@trpc/server'
const t = initTRPC.create()
export const router = t.router
export const middleware = t.middleware
export const publicProcedure = t.procedure
创建项目(根)路由文件 pages/api/trpc/[trpc].ts
import * as trpc from '@trpc/server'
import { publicProcedure, router } from './trpc'
const appRouter = router({
greeting: publicProcedure.query(() => 'hello tRPC!'),
})
export type AppRouter = typeof appRouter
此时已经定义好了一个路由地址 api/trpc/[trpc].ts
(这里 endpoint(端点)会在客户端中使用到),以及 greeting
函数,服务端的工作就暂且完毕。
创建客户端
创建 utils/trpc.ts
文件,代码如下
import { httpBatchLink } from '@trpc/client'
import { createTRPCNext } from '@trpc/next'
import type { AppRouter } from '../pages/api/trpc/[trpc]'
function getBaseUrl() {
if (typeof window !== 'undefined') {
// In the browser, we return a relative URL
return ''
}
// When rendering on the server, we return an absolute URL
// reference for vercel.com
if (process.env.VERCEL_URL) {
return `https://${process.env.VERCEL_URL}`
}
// assume localhost
return `http://localhost:${process.env.PORT ?? 3000}`
}
export const trpc = createTRPCNext<AppRouter>({
config() {
return {
links: [
httpBatchLink({
url: getBaseUrl() + '/api/trpc',
}),
],
}
},
})
在 _app.tsx
包装一下
import type { AppType } from 'next/app'
import { trpc } from '../utils/trpc'
const MyApp: AppType = ({ Component, pageProps }) => {
return <Component {...pageProps} />
}
export default trpc.withTRPC(MyApp)
有了这个对象后,我们就可以开始尽情调用服务端所定义好了函数了
还需补充,但是没时间,嘿嘿
在 nestjs 中使用
作者 | 链接 |
---|---|
愧怍 | Typescript 全栈最值得学习的技术栈 TRPC |