
如何快速實現(xiàn)REST API集成以優(yōu)化業(yè)務流程
"imports": {
"@std/path": "jsr:@std/path@^1.0.6",
"@trpc/client": "npm:@trpc/client@^11.0.0-rc.593",
"@trpc/server": "npm:@trpc/server@^11.0.0-rc.593",
"zod": "npm:zod@^3.23.8"
}
}
構建我們的 tRPC 應用程序的第一步是設置服務器。我們將從初始化 tRPC 和創(chuàng)建基礎路由器和過程構建器開始。這些將是我們定義 API 端點的基礎。
創(chuàng)建一個?server/trpc.ts
?文件:
// server/trpc.ts
import { initTRPC } from "@trpc/server";
/**
* Initialization of tRPC backend
* Should be done only once per backend!
*/
const t = initTRPC.create();
/**
* Export reusable router and procedure helpers
* that can be used throughout the router
*/
export const router = t.router;
export const publicProcedure = t.procedure;
這初始化了 tRPC 并導出了我們將用于定義 API 端點的路由器和過程構建器。publicProcedure
?允許我們創(chuàng)建不需要身份驗證的端點。
接下來,我們將創(chuàng)建一個簡單的數(shù)據(jù)層來管理我們的恐龍數(shù)據(jù)。創(chuàng)建一個?server/db.ts
?文件:
// server/db.ts
import { join } from "@std/path";
type Dino = { name: string; description: string };
const dataPath = join("data", "data.json");
async function readData(): Promise<Dino[]> {
const data = await Deno.readTextFile(dataPath);
return JSON.parse(data);
}
async function writeData(dinos: Dino[]): Promise<void> {
await Deno.writeTextFile(dataPath, JSON.stringify(dinos, null, 2));
}
export const db = {
dino: {
findMany: () => readData(),
findByName: async (name: string) => {
const dinos = await readData();
return dinos.find((dino) => dino.name === name);
},
create: async (data: { name: string; description: string }) => {
const dinos = await readData();
const newDino = { ...data };
dinos.push(newDino);
await writeData(dinos);
return newDino;
},
},
};
這創(chuàng)建了一個簡單的基于文件的數(shù)據(jù)庫,它將恐龍數(shù)據(jù)讀取和寫入到一個 JSON 文件中。在生產環(huán)境中,你通常會使用一個合適的數(shù)據(jù)庫,但這對我們的演示來說已經(jīng)足夠了。
??? 在本教程中,我們硬編碼數(shù)據(jù)并使用基于文件的數(shù)據(jù)庫。然而,你可以連接到各種數(shù)據(jù)庫并使用 ORM,如 Drizzle 或 Prisma。
最后,我們需要提供實際的數(shù)據(jù)。讓我們創(chuàng)建一個?./data.json
?文件,其中包含一些示例恐龍數(shù)據(jù):
[
{
"name": "Aardonyx",
"description": "An early stage in the evolution of sauropods."
},
{
"name": "Abelisaurus",
"description": "\"Abel's lizard\" has been reconstructed from a single skull."
},
{
"name": "Abrictosaurus",
"description": "An early relative of Heterodontosaurus."
},
{
"name": "Abrosaurus",
"description": "A close Asian relative of Camarasaurus."
},
...
]
現(xiàn)在,我們可以創(chuàng)建我們的主服務器文件,它定義了我們的 tRPC 路由器和過程。創(chuàng)建一個?server/index.ts
?文件:
import { createHTTPServer } from "@trpc/server/adapters/standalone";
import { z } from "zod";
import { db } from "./db.ts";
import { publicProcedure, router } from "./trpc.ts";
const appRouter = router({
dino: {
list: publicProcedure.query(async () => {
const dinos = await db.dino.findMany();
return dinos;
}),
byName: publicProcedure.input(z.string()).query(async (opts) => {
const { input } = opts;
const dino = await db.dino.findByName(input);
return dino;
}),
create: publicProcedure
.input(z.object({ name: z.string(), description: z.string() }))
.mutation(async (opts) => {
const { input } = opts;
const dino = await db.dino.create(input);
return dino;
}),
},
examples: {
iterable: publicProcedure.query(async function* () {
for (let i = 0; i < 3; i++) {
await new Promise((resolve) => setTimeout(resolve, 500));
yield i;
}
}),
},
});
// Export type router type signature, this is used by the client.
export type AppRouter = typeof appRouter;
const server = createHTTPServer({
router: appRouter,
});
server.listen(3000);
這設置了三個主要端點:
dino.list
:返回所有恐龍dino.byName
:按名稱返回特定恐龍dino.create
:創(chuàng)建一個新的恐龍examples.iterable
:演示 tRPC 對 async iterables 的支持服務器配置為監(jiān)聽 3000 端口,并將處理所有 tRPC 請求。
雖然你現(xiàn)在可以運行服務器,但你將無法訪問任何路由并返回數(shù)據(jù)。讓我們來解決這個問題!
我們的服務器準備好了,我們可以創(chuàng)建一個客戶端,它以完全類型安全的方式使用我們的 API。創(chuàng)建一個?client/index.ts
?文件:
// client/index.ts
/**
* This is the client-side code that uses the inferred types from the server
*/
import {
createTRPCClient,
splitLink,
unstable_httpBatchStreamLink,
unstable_httpSubscriptionLink,
} from "@trpc/client";
/**
* We only import the AppRouter
type from the server - this is not available at runtime
*/
import type { AppRouter } from "../server/index.ts";
// Initialize the tRPC client
const trpc = createTRPCClient<AppRouter>({
links: [
splitLink({
condition: (op) => op.type === "subscription",
true: unstable_httpSubscriptionLink({
url: "http://localhost:3000",
}),
false: unstable_httpBatchStreamLink({
url: "http://localhost:3000",
}),
}),
],
});
const dinos = await trpc.dino.list.query();
console.log("Dinos:", dinos);
const createdDino = await trpc.dino.create.mutate({
name: "Denosaur",
description:
"A dinosaur that lives in the deno ecosystem. Eats Nodes for breakfast.",
});
console.log("Created dino:", createdDino);
const dino = await trpc.dino.byName.query("Denosaur");
console.log("Denosaur:", dino);
const iterable = await trpc.examples.iterable.query();
for await (const i of iterable) {
console.log("Iterable:", i);
}
這段客戶端代碼展示了 tRPC 的幾個關鍵特性:
AppRouter
?類型導入繼承所有類型定義。這意味著你將獲得完整的類型支持和編譯時類型檢查,適用于你所有的 API 調用。如果你在服務器上修改了一個過程,TypeScript 將立即標記任何不兼容的客戶端使用。list
和 byName
)和用于修改服務器端狀態(tài)的操作(create
)。客戶端自動知道每個過程的輸入和輸出類型,在整個請求周期中提供類型安全性。examples.iterable
演示了 tRPC 對使用異步可迭代對象流式傳輸數(shù)據(jù)的支持。這個特性特別適合實時更新或分塊處理大型數(shù)據(jù)集。現(xiàn)在,讓我們啟動服務器來看看它在行動中的樣子。在我們的?deno.json
?配置文件中,讓我們創(chuàng)建一個新屬性?tasks
,包含以下命令:
{
"tasks": {
"start": "deno -A server/index.ts",
"client": "deno -A client/index.ts"
}
}
deno task
?列出可用的任務:deno task
Available tasks:
- start
deno -A server/index.ts
- client
deno -A client/index.ts
現(xiàn)在,我們可以使用?deno task start
?啟動服務器。之后,我們可以使用?deno task client
?運行客戶端。你應該看到像這樣的輸出:
deno task client
Dinos: [
{
name: "Aardonyx",
description: "An early stage in the evolution of sauropods."
},
{
name: "Abelisaurus",
description: "Abel's lizard has been reconstructed from a single skull."
},
{
name: "Abrictosaurus",
description: "An early relative of Heterodontosaurus."
},
...
]
Created dino: {
name: "Denosaur",
description: "A dinosaur that lives in the deno ecosystem. Eats Nodes for breakfast."
}
Denosaur: {
name: "Denosaur",
description: "A dinosaur that lives in the deno ecosystem. Eats Nodes for breakfast."
}
Iterable: 0
Iterable: 1
Iterable: 2
成功!運行?./client/index.ts
?展示了如何創(chuàng)建一個 tRPC 客戶端并使用其 JavaScript API 與數(shù)據(jù)庫交互。但是我們如何檢查 tRPC 客戶端是否正確地從數(shù)據(jù)庫推斷類型呢?讓我們在?./client/index.ts
?中修改下面的代碼片段,將?description
?傳遞一個?number
?而不是?string
:
// ...
const createdDino = await trpc.dino.create.mutate({
name: "Denosaur",
description:
- "A dinosaur that lives in the deno ecosystem. Eats Nodes for breakfast.",
+ 100,
});
console.log("Created dino:", createdDino);
// ...
deno task client
...
error: Uncaught (in promise) TRPCClientError: [
{
"code": "invalid_type",
"expected": "string",
"received": "number",
"path": [
"description"
],
"message": "Expected string, received number"
}
]
at Function.from (file:///Users/andyjiang/Library/Caches/deno/npm/registry.npmjs.org/@trpc/client/11.0.0-rc.608/dist/TRPCClientError.mjs:35:20)
at file:///Users/andyjiang/Library/Caches/deno/npm/registry.npmjs.org/@trpc/client/11.0.0-rc.608/dist/links/httpBatchStreamLink.mjs:118:56
at eventLoopTick (ext:core/01_core.js:175:7)
tRPC 成功拋出了一個 invalid_type
錯誤,因為它期望一個 string
而不是 number
。
現(xiàn)在你對如何使用 Deno 和 tRPC 有了基本的了解,你可以:
?? 祝你在使用 Deno 和 tRPC 進行類型安全編碼時愉快!參考資料[1]
源碼:?https://github.com/denoland/examples/tree/main/with-trpc
本文章轉載微信公眾號@前端與Deno