🐇

Next.jsでGraphQLを使用するためのcodegenとurqlの設定方法

公開日
10か月前
2023-10-02
更新日
20日前
2024-07-06
更新履歴

GraphQL Code GeneratorでTypeScriptの型定義を生成できるようにする

GraphQL Code GeneratorでGraphQLのスキーマからTypeScriptの型定義を生成するための環境構築をします。

Next.jsのインストールとESLint・Prettierのセットアップで作成した環境に構築していきます。

インストール

下記の二つのコマンドで必要なパッケージをインストールします。Next.jsでも使用する環境変数の設定をGraphQL codegenからも使用するために dotenv をインストールしています。

pnpm add -E graphql @graphql-typed-document-node/core
pnpm add -D -E @graphql-codegen/cli @graphql-codegen/client-preset dotenv

設定ファイルを作成

.env.development.localに下記の内容を追記します。

API_ENDPOINT=http://localhost/graphql
API_ACCESS_TOKEN=HOGEHOGE

codegen.tsを下記の内容で作成します。pnpm dlx graphql-code-generator init で作成しても良いです。

codegen.ts
require('dotenv').config({ path: '.env.development.local' })

import { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: {
    [`${process.env.API_ENDPOINT}`]: {
      headers: {
        Authorization: `Bearer ${process.env.API_ACCESS_TOKEN}`,
      },
    },
  },
  documents: ['src/**/*.{ts,tsx}'],
  ignoreNoDocuments: true,
  generates: {
    'src/gql/': {
      preset: 'client',
      presetConfig: {
        fragmentMasking: { unmaskFunctionName: 'getFragmentData' },
      },
      plugins: [],
    },
  },
  hooks: { afterAllFileWrite: ['pnpx prettier --write', 'pnpx eslint --fix'] },
}

export default config

package.jsonの修正

package.json
"scripts": {
  "codegen": "gql-gen --config codegen.ts"
}

urqlの設定をする

GraphQLのクライアントとして urql を使います。キャッシュ周りがシンプルなので使いやすいです。

Next.jsのServer Componentsから使う場合の解説のみ行います。

urqlをインストール

pnpm add -E @urql/core @urql/next

クライアントの作成

下記のファイルを作成します。

src/urql/client.ts
import { cacheExchange, createClient, fetchExchange } from '@urql/core'
import { registerUrql } from '@urql/next/rsc'

function makeClient() {
  return createClient({
    url: `${process.env.API_ENDPOINT}`,
    exchanges: [cacheExchange, fetchExchange],
    fetchOptions: {
      headers: {
        Authorization: `bearer ${process.env.API_ACCESS_TOKEN}`,
      },
    },
  })
}

export const { getClient } = registerUrql(makeClient)

GraphQLでデータを取得する

下記のようなコードでデータの取得ができます。src/app/page.tsx などで試してみてください。

pnpm codegen を実行することで DocumentDocument の型が生成されます。

src/app/page.tsx
import { graphql } from '@/gql'
import { DocumentDocument } from '@/gql/graphql'
import { getClient } from '@/urql/client'

graphql(`
  query document($slug: String) {
    document(slug: $slug) {
      id
    }
  }
`)

export default async function Home() {
  const { data, error } = await getClient().query(DocumentDocument, {
    slug: 'hoge',
  })

  return <>{data.document?.id}</>
}