0
1

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.

Next.jsでAPIサーバーを実装する時APIレスポンスに型をつける方法

Posted at

はじめに

APIサーバーを構築する際、型を活用することで開発スピードを劇的に改善できます。Next.jsはReactをベースに構築されたフレームワークであり、TypeScript対応もしているため、型に関する様々な恩恵を受けることができます。本記事では、APIサーバーのレスポンスに型をつける方法を紹介します。

やり方 手順

  1. まずはじめに、次のようにNextApiResponseに型を記述するインターフェースを用意します。
interface ApiResponse<T> extends NextApiResponse {
  status: number;
  data: T;
}

この中で、Tにはレスポンスの型を記述していきます。

  1. 次に、APIのエンドポイントである関数の例を示します。
export default async function handler(
  req: NextApiRequest,
  res: ApiResponse<{ message: string }>
) {
  try {
    const message = 'API response';
    res.status(200).json({ message });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: error.message });
  }
}

handler関数内では、ApiResponse型を使ってresの型を指定しました。{ message: string }はレスポンスで渡すデータの型を表します。このようにすることで、TypeScriptがコンパイル時に型チェックを行い、想定しないエラーが発生することを防止できます。

  1. 最後に、次のようにhelperの関数を使って、オブジェクトを生成します。
export function ApiResponse<T>(res: NextApiResponse, data: T, status: number = 200): void {
  res.status(status).json({ data, status });
}

これにより、レスポンスの内容を効率的かつ簡素に構築することができます。

注意点、補足

  • ApiResponseはインターフェースとして定義されていますが、関数として使用できます。
  • ApiResponseの定義でNextApiResponseを継承しているため、その他のNextApiResponseのメソッドも使用できます。

以上が、Next.jsでAPIサーバーを構築する際にNextApiResponseに型をつける方法の紹介でした。規模の大きいプロジェクトでは、型チェックが必要不可欠なので、ぜひ型を活用して開発を進めてみてください。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?