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?

日記:fetch() フェッチAPI について少し解像度が上がった。

Last updated at Posted at 2025-09-19

Next.jsのキャッシュ削除のPRをレビューしていて、以下のようなコードに出会った。

  const fetchOptions: RequestInit = {
    method: "GET",
    ...(cache || {}),
    next: {
      tags: ["stepItem"],
      ...(cache?.next || {}),
    },
    cache: "force-cache",
  };

  const response = await fetchWithTokenRefresh(url, fetchOptions);
  • とあるurlから情報を取るために、APIを叩くfetchWithTokenRefresh() をしている
  • このとき第一引数が url, 第二引数が fetchOptions
  • fetchOptionsの型は RequestInit
export default async function fetchWithTokenRefresh(
  url: string,
  options: RequestInit,
  apiVersion = "v1",
) {

RequestInitって何だ

image.png

型 RequestInitの定義もとが三つあった。
ん?どうやって使い分けてるんや?と思った。けどそこは一旦飛ばす。

定義もとにジャンプして、

  • 標準のFetch APIの引数としてのReqestInitがあること
  • Next.js拡張 によりcacheとnextプロパティを追加していること
    がわかった

以下の記事を読んだ。

https://developer.mozilla.org/ja/docs/Web/API/Fetch_API/Using_Fetch
https://developer.mozilla.org/ja/docs/Web/API/RequestInit

気づいたこと

  • PRレビューによって、コーディングの解像度が上がる

理由は、

  • 自分が書いたコードはローカルで動けばいい。PRで見てもらう。みたいな責任感のないことができる。(最悪)
  • だけど、自分がreviewerになってmergeをする責任を持つと本番でエラーを起こさない。将来的にもエラーを起こさないことを保証する必要があるから、深く読み込むため

複数ある時の型解決の仕組み

TypeScriptは以下の巧妙な条件分岐で適切な定義を選択する:

1.環境検出のロジック

  • ブラウザ環境: onmessageプロパティが存在する → DOM版を使用
  • Node.js環境: onmessageプロパティが存在しない → undici版を使用

2.tsconfig.jsonでの制御

  • "dom"が含まれているため、ブラウザ環境としてDOMのRequestInitが基本となる
  • しかし、Node.js環境では@types/nodeの条件分岐により上書きされる

3.実際の適用順序

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?