trpc 基于typescript的api 开放框架
trpc 是一个类型安全的api 开发框架,可以利用typescript 强大的类型能力,同时也能实现数据处理的复用,以下是一个参考案例
参考demo
- server 端代码
package.json
{
"dependencies": {
"@trpc/client": "^7.3.3",
"@trpc/next": "^7.3.3",
"@trpc/react": "^7.3.3",
"@trpc/server": "^7.3.3",
"express": "^4.17.1",
"node-fetch": "^2.6.1"
},
"devDependencies": {
"@types/express": "^4.17.12",
"@types/node": "^15.12.4",
"@types/node-fetch": "^2.5.10"
},
"name": "trpc-app",
"version": "1.0.0",
"main": "index.js",
"license": "MIT"
}
app.ts
// server/index.ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router().query('getUser', {
input: (val: unknown) => {
if (typeof val === 'string') return val;
throw new Error(`Invalid input: ${typeof val}`);
},
async resolve(req) {
req.input; // string
return { id: req.input, name: 'Bilbo' };
},
});
export default appRouter;
export type AppRouter = typeof appRouter;
express 集成
import * as trpcExpress from '@trpc/server/adapters/express';
import * as trpc from '@trpc/server';
import appRouter from "./app"
import express from "express"
const app = express();
// created for each request
const createContext = ({
req,
res,
}: trpcExpress.CreateExpressContextOptions) => ({}) // no context
type Context = trpc.inferAsyncReturnType<typeof createContext>;
app.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router: appRouter,
createContext: () => null, // no context
})
);
app.listen(4000);
- client 代码
import type { AppRouter } from './app';
import { createTRPCClient } from '@trpc/client';
import fetch from "node-fetch"
// 此处比较重要
global.fetch = fetch as any;
const client = createTRPCClient<AppRouter>({
url: 'http://localhost:4000/trpc',
});
(async()=>{
const bilbo = await client.query('getUser', 'id_bilbo');
console.log(bilbo)
})()
说明
trpc 是一个很不错的基于typescript 开发api 的框架,而且目前已经提供了比较完备的框架支持(react,next,express)