GraphQL Code GeneratorでTypeScriptのコードを生成してみる
GraphQL Code Generatorで以下の2つの要望を満たす設定をする。
- aliasで指定したfield名の型定義を生成したい
- リクエストクエリをstring型の変数で生成したい
最初に結論として、codegen.ymlに以下のような設定にする。schemaやdocuments、出力先は環境によって変える必要がある。また、3つのプラグインはパッケージをインストールしておく必要がある。
# codegen.yml schema: schema.graphql documents: src/**/*.graphql generates: src/generated/graphql.ts: plugins: - typescript - typescript-operations - typescript-graphql-request config: documentMode: string
例としてスキーマは以下とする(https://www.graphql-code-generator.com/docs/getting-started/indexから拝借した)。
# schema.graphl type Author { id: Int! firstName: String! lastName: String! posts(findTitle: String): [Post] } type Post { id: Int! title: String! author: Author! } type Query { posts: [Post] } schema { query: Query }
リクエストクエリは以下とする。aliasでauthorも含めたpostsをpostsWithAuthorとして取得する。あくまで例なので実際にこのようなクエリを書くかは問わない。
# src/graphql/getPosts.graphql query getPosts { posts: posts { id title } postsWithAuthor: posts { id title author { id firstName lastName } } }
生成コマンドを実行すると以下のコードが生成される。他にも様々な型定義が出力されるが、必要なコードだけ抜粋している。
// src/generated/graphql.ts export type GetPostsQuery = { __typename?: 'Query', posts?: Maybe<Array<Maybe<{ __typename?: 'Post', id: number, title: string }>>>, postsWithAuthor?: Maybe<Array<Maybe<{ __typename?: 'Post', id: number, title: string, author: { __typename?: 'Author', id: number, firstName: string, lastName: string } }>>> }; export const GetPostsDocument = ` query getPosts { posts: posts { id title } postsWithAuthor: posts { id title author { id firstName lastName } } } `;
GetPostsQueryにaliasで指定したpostsWithAuthorが含まれているので要望1を満たしている。GetPostsDocumentが要望2を満たしている。
サンプルコード -> https://github.com/azujuuuuuun/try-graphql-code-generator