# GraphQL Code Generator ###### tags: `GraphQL` # 前提条件 json-grapql-serverがセットアップされた状態 # インストール ```shell= yarn add graphql ``` ```shell= yarn add -D @graphql-codegen/cli ``` :::warning 🐝 上記2つをグローバルインストールはNG(cliパッケージはgraphqlに依存しているから) ::: # configファイルを作成する ```shell= yarn graphql-codegen init ``` # codegen.ymlを編集する **src/apollo/codegen.yml** ```yaml= # graphqlサーバーのエンドポイント schema: "http://localhost:4000" # どのコードを見るか documents: "src/**/*.{ts,tsx,graphql}" overwrite: true generates: # generateしたファイルをどこに作成するか src/apollo/gql.tsx: plugins: - "typescript" - "typescript-operations" - "typescript-react-apollo" config: - skipTypename: false - withHooks: true - withHOC: false - withComponent: false - preResolveTypes: false - namingConvention: - typeNames: "pascal-case#pascalCase" - enumValues: "upper-case#upperCase" - scalars: - uuid: "string" - timestamptz: "string" - bigint: "number" - _text: "string[]" - apolloReactCommonImportFrom: "@apollo/client" - apolloReactHooksImportFrom: "@apollo/client" # スキーマを検索するファイル src/apollo/graphql.schema.json: plugins: - "introspection" ``` # GraphQLのサーバーにアクセスできるようにアプリをラップ **src/apollo/apollo-client.ts** ```typescript= import { ApolloClient, InMemoryCache } from "@apollo/client"; export const client = new ApolloClient({ uri: "http://localhost:4000/", cache: new InMemoryCache(), }); ``` **src/pages/_app.tsx** ```typescript= import "src/styles/globals.css"; import { ApolloProvider } from "@apollo/client"; import type { NextPage } from "next"; import type { AppProps } from "next/app"; import { client } from "src/apollo/apollo-client"; const MyApp: NextPage<AppProps> = (props) => { return ( <ApolloProvider client={client}> <props.Component {...props.pageProps} /> </ApolloProvider> ); }; // eslint-disable-next-line import/no-default-export export default MyApp; ``` # 拡張子".graphql"のファイルにクエリー文を書いてみる **src/components/allPostsQuery.graphql** ```graphql= query Posts { allPosts { id title views userId } } ``` # codegenコマンドをscriptに登録する **package.json** ```json= { "scripts": { "codegen": "graphql-codegen --config src/apollo/codegen.yml" } } ``` # codegenを起動して、"gql.tsx"と"graphql.schema.json"をsrc/apollo/配下に生成する ```shell= yarn codegen ``` # gql.tsxに作成されたカスタムフックを使用してjson-graphql-serverからデータを取得してみる **src/components/CodegenUseSample.tsx** ```jsx= import { gql } from "@apollo/client"; import type { FC } from "react"; import { usePostsQuery } from "src/apollo/gql"; export const CodegenUseSample: FC = () => { // hooksを自動で生成してくれる(しかも戻り値の型定義済み) const { data, loading, error } = usePostsQuery(); if (loading) { <div>loading...</div>; } if (error) { <div>Error</div>; } return ( <div key="rate"> <h3>graphql-code-generator</h3> <table> <thead> <tr> <th>PID</th> <th>PostTitle</th> <th>PostViews</th> <th>CreateUId</th> </tr> </thead> <tbody> {data?.allPosts?.map((posts, index) => { return ( <tr key={index}> <td>{posts?.id}</td> <td>{posts?.title}</td> <td>{posts?.views}</td> <td>{posts?.userId}</td> </tr> ); })} </tbody> </table> </div> ); }; // 変数としてexportすることもできるけど、ここで定義してれば勝手にcodegenが探してこのクエリーに関する型定義ファイル作ってくれる gql` query Posts { allPosts { id title views userId } } `; ```