2
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?

【React】GraphQL Codegenの「arrayInputCoercion」設定について

Posted at

概要

ジャンルなしオンラインもくもく会 Advent Calendar 2025、13日目の記事になります。
表題の通り、GraphQL CodegenにはarrayInputCoercionという設定があります。直訳すると配列入力の強制となるのですが、設定名だけだとピンとこなかったので内容をメモ書きします。

前提

  • Codegenにはclient-presetを使用します。「@graphql-codegen/client-preset」のバージョンは5.1.3を使用しました。

設定内容について

Client presetのドキュメントに、「arrayInputCoercion」の説明が書いてあります。説明を要約するとGraphQLでの規定の仕様では、配列で定義した項目には配列およびそのオブジェクト単体でも設定可能であるとのこと。で、「arrayInputCoercion」を設定することで、GraphQLでの規定の仕様ではなく、純粋に配列型だけ受け付けるようにすることが可能になります。
「arrayInputCoercion」は無設定だとデフォルトでtrueになるので配列およびその単体のオブジェクト型が出力されるのですが、falseに設定すると配列のみを受け付ける型が出力されます。

実装サンプル

「schema.graphqls」で以下のような定義を用意します。

schema.graphqls
type Mutation {
  registerNovelContents(inputs: [NovelContentsRegisterInput!]!): Boolean
}

codegenの設定で、arrayInputCoercionを設定せず(trueの状態)で型を生成すると以下のように出力されます。

graphql.ts
export type RegisterNovelSettingsMutationVariables = Exact<{
  inputs: Array<NovelSettingRegisterInput> | NovelSettingRegisterInput;
}>;

codegenの設定で、arrayInputCoercionをfalseにすると、以下のように出力されます。

graphql.ts
export type RegisterNovelSettingsMutationVariables = Exact<{
  inputs: Array<NovelSettingRegisterInput>;
}>;
2
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
2
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?