0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

タイトル: 「初心者でも分かる!tRPCで型安全なAPIを手軽に実現する方法」

Posted at

目次

  1. はじめに
  2. tRPCとは何か?
  3. TypeScriptとtRPCの組み合わせの強み
  4. tRPCの基本的な使用例
  5. 実際のコード例
  6. まとめ

はじめに

API開発における型安全は重要なテーマです。tRPCとTypeScriptを組み合わせることで、初心者でも手軽に型安全なAPI開発ができます。この記事では、tRPCの基本から実際のコード例までを解説します。

tRPCとは何か?

tRPCは、サーバーとクライアント間で型情報を共有するためのツールです。このセクションではtRPCの概要とメリットについて説明します。

型安全

型エラーをコンパイル時に検出できるため、ランタイムエラーを削減します。

TypeScriptとtRPCの組み合わせの強み

TypeScriptと組み合わせることで、tRPCはより強力になります。このセクションではその理由と利点について解説します。

tRPCの基本的な使用例

ここでは、ウェブサイトの管理者が訪問者の情報を取得する一般的なケースを例に、tRPCの基本的な使用方法を説明します。

実際のコード例

サーバー側のコード

import { createTRPCRouter } from '@trpc/server';

const router = createTRPCRouter()
  .query('getUser', {
    resolve() {
      return { id: 1, name: 'Bilbo' };
    },
  });

// Expressとの統合例
import express from 'express';
import { inferAsyncReturnType } from '@trpc/server';
import { z } from 'zod';

type Context = inferAsyncReturnType<typeof createContext>;

const createContext = async ({ req, res }: express.Request) => ({ req, res });
const app = express();
app.use('/trpc', trpcExpress.createExpressMiddleware({ router, createContext }));

クライアント側のコード

import { createTRPCClient } from '@trpc/client';

const trpc = createTRPCClient({
  url: '/trpc',
});

// getUserクエリの使用例
const user = await trpc.query('getUser');
console.log(user.id, user.name); // 1, 'Bilbo'

まとめ

tRPCは、初心者でも手軽に型安全なAPI開発を実現できる強力なツールです。この記事を通じてtRPCの基本を学び、実際のプロジェクトに活用する方法について理解を深めることができたことでしょう。

ぜひ自分のプロジェクトでtRPCを使ってみて、その強力な型安全機能を体感してください!


この記事の構造と内容は、初心者にもわかりやすく、具体的なコード例も提供しています。Qiitaのフォーマットに従い、読者に興味を持ってもらえる内容になるよう工夫しています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?