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?

HonoのRPCを用いたDB管理を効率化する方法

Posted at

皆さん、こんにちは。

今回は【HonoのRPCを用いたDB管理を効率化する方法】について紹介させていただきます。

近年、Hono は「超軽量かつ高速なWebフレームワーク」として注目を集めています。
特に Cloudflare Workers や Deno Deploy, Bun のようなサーバーレス環境で利用するケースが増えています。

一方で、API開発においてよくある課題が「フロントエンドとバックエンド間の型ズレ」や「API定義の重複」です。
これを解決するのが、Hono公式が提供する RPC (Remote Procedure Call) 機能です。

背景

通常、フロントエンドとバックエンドの通信は REST や GraphQL を用いて行われます。
しかし、開発規模が小さい場合や、型安全性を重視する場合にはRPCスタイルのAPIが有効です。

Honoでは、@hono/rpc パッケージを用いることで、API関数を直接呼び出すように通信できる構成を実現できます。

プロジェクト構成例

project/
├── src/
│   ├── server/
│   │   ├── index.ts
│   │   ├── db.ts
│   │   └── routes.ts
│   ├── client/
│   │   └── rpcClient.ts
│   └── types/
│       └── rpc.ts
├── package.json
└── tsconfig.json

サーバー側の実装

DB接続を用意する(例:Prisma)

// src/server/db.ts
import { PrismaClient } from '@prisma/client'

export const db = new PrismaClient()

RPCハンドラーを定義

// src/server/routes.ts
import { db } from './db'
import { rpc } from '@hono/rpc'

export const app = rpc({
  async getUsers() {
    return db.user.findMany()
  },

  async addUser(input: { name: string; email: string }) {
    return db.user.create({ data: input })
  },

  async deleteUser(id: number) {
    return db.user.delete({ where: { id } })
  },
})

サーバーを起動

// src/server/index.ts
import { Hono } from 'hono'
import { app as rpcApp } from './routes'

const server = new Hono()
server.route('/rpc', rpcApp)

export default server

クライアント側の実装

RPCクライアントを生成

// src/client/rpcClient.ts
import { hc } from 'hono/client'
import type { AppType } from '../types/rpc'

const client = hc<AppType>('/rpc')

export const rpc = {
  getUsers: () => client.getUsers.$get(),
  addUser: (input) => client.addUser.$post({ json: input }),
  deleteUser: (id) => client.deleteUser.$delete({ param: { id } }),
}

Reactなどで利用

// example in React
import { useEffect, useState } from 'react'
import { rpc } from './rpcClient'

export function UserList() {
  const [users, setUsers] = useState([])

  useEffect(() => {
    rpc.getUsers().then(setUsers)
  }, [])

  return (
    <div>
      <h1>ユーザー一覧</h1>
      <ul>
        {users.map((u) => (
          <li key={u.id}>{u.name}</li>
        ))}
      </ul>
    </div>
  )
}

まとめ

HonoのRPCを用いることで、「型安全で、フロントとバックの整合性が保たれたDB操作」 を簡潔に実現できます。

小規模~中規模のアプリケーションや、Bun / Cloudflare Workers / Deno Deploy 環境などでの開発に非常に相性が良いです。

今日は以上です。

ありがとうございました。
よろしくお願いいたします。

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?