メインコンテンツへスキップ
バージョン: 9.x

クイックスタート

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

ヒント

tRPCの感触をできるだけシームレスに得て、起動・実行できるように、サンプルアプリをぜひチェックすることをお勧めします。

インストール

⚠️ 必要条件: tRPCはテンプレートリテラル型に依存しているため、TypeScript > 4.1が必要です。

npm install @trpc/server

tRPCエンドポイントとルーターの実装用。サーバーコードベースにインストールします。

npm install @trpc/client @trpc/server

クライアントからの型安全なAPI呼び出し用。クライアントコードベースにインストールします(@trpc/server@trpc/clientのピア依存関係です)。

npm install @trpc/react react-query@3

tRPC APIをクエリするための強力なReactフックセットの生成用。react-queryによって動作します。

npm install @trpc/next

tRPCとNext.jsを統合するためのユーティリティセット。

インストールスニペット

npm:

bash
npm install @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next
bash
npm install @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next

yarn:

bash
yarn add @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next
bash
yarn add @trpc/server @trpc/client @trpc/react react-query@3 @trpc/next

ルーターの定義

tRPCを使用して型安全なAPIを構築する手順を順を追って説明します。まず、このAPIには2つのエンドポイントのみを含めることにします:

ts
getUser(id: string) => { id: string; name: string; }
createUser(data: {name:string}) => { id: string; name: string; }
ts
getUser(id: string) => { id: string; name: string; }
createUser(data: {name:string}) => { id: string; name: string; }

ルーターインスタンスの作成

まずサーバーコードベースのどこかでルーターを定義します:

server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router();
// only export *type signature* of router!
// to avoid accidentally importing your API
// into client-side code
export type AppRouter = typeof appRouter;
server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router();
// only export *type signature* of router!
// to avoid accidentally importing your API
// into client-side code
export type AppRouter = typeof appRouter;

クエリーエンドポイントの追加

.query()メソッドを使用してクエリーエンドポイントをルーターに追加します。引数は以下の通りです:

.query(name: string, params: QueryParams)

  • name: string: このエンドポイントの名前

  • params.input: オプション。このエンドポイントへの入力値を検証/変換し、型安全な値(有効な場合)を返すか、エラーをスロー(無効な場合)する関数を指定します。代わりにZodSuperstructYupのスキーマを渡すこともできます。

  • params.resolve: エンドポイントの実際の実装です。req引数を1つ持つ関数です。検証済みの入力はreq.inputに渡され、コンテキストはreq.ctxに含まれます(コンテキストについての詳細は後述!)

server.ts
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 type AppRouter = typeof appRouter;
server.ts
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 type AppRouter = typeof appRouter;

ミューテーションエンドポイントの追加

GraphQLと同様に、tRPCはクエリーとミューテーションのエンドポイントを区別します。createUserミューテーションを追加してみましょう:

ts
createUser(payload: {name: string}) => {id: string; name: string};
ts
createUser(payload: {name: string}) => {id: string; name: string};
server.ts
ts
import * as trpc from '@trpc/server';
import { z } from 'zod';
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' };
},
})
.mutation('createUser', {
// validate input with Zod
input: z.object({ name: z.string().min(5) }),
async resolve(req) {
// use your ORM of choice
return await UserModel.create({
data: req.input,
});
},
});
export type AppRouter = typeof appRouter;
server.ts
ts
import * as trpc from '@trpc/server';
import { z } from 'zod';
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' };
},
})
.mutation('createUser', {
// validate input with Zod
input: z.object({ name: z.string().min(5) }),
async resolve(req) {
// use your ORM of choice
return await UserModel.create({
data: req.input,
});
},
});
export type AppRouter = typeof appRouter;

次のステップ

tRPCには、一般的なReactプロジェクト向け、特にNext.js向けに設計されたより洗練されたクライアントサイドツールが含まれています。次に適切なガイドを参照してください: