📊

【Rails × GraphQL】「Second definition of mutation(...)」の修正方法

に公開

エラー解決:「Second definition of mutation(...)」の修正方法

今回、GraphQL の定義ファイルで以下のエラーに遭遇しました。

"message": "Second definition of `mutation(...)`
 (Example::Types::ExampleMutationType) is invalid, already configured with
Example::Types::ExampleMutationType"

結論(私の場合)

結論から申し上げると、このエラーの原因は description が重複している構文ミスでした。
つまり、うっかり構文エラーです。

誤ったコード

誤ったコードを以下に示します。

field :items, [Example::Types::ItemType], null: false,
      description: 'Fetches all items.' do # 重複
      description: 'Fetches items with optional filters.' do # 重複
  argument :category, String, required: false,
            description: 'カテゴリー(例:書籍、雑貨)'
  argument :search_key, String, required: false,
            description: '検索キーワード'
end

このコードの問題点は、field 定義内で description が2回記述されていることです。

(少々余談ですが) GraphQL の field 定義では、引数 argument とは異なり field 自体に設定できる description は1つのみです。後から記述された description によって上書きまたはエラーが発生します。

https://graphql-ruby.org/fields/resolvers.html#when-do-you-really-need-a-resolver
cf): サンプルコードのように、argument は複数定義できる。

修正後のコード

以下のように、descriptionを1つに統合します。

field :items, [Example::Types::ItemType], null: false,
      description: 'Fetches items with optional filters.' do
  argument :category, String, required: false,
            description: 'カテゴリー(例:書籍、雑貨)'
  argument :search_key, String, required: false,
            description: '検索キーワード'
end

この修正でエラーが解消されます。

修正後のコード解説

GraphQL では1つのフィールドに対して複数の description を定義できません。そのため、以下のように1つのフィールドに1つの説明を与えるよう統一する必要があります。

再掲:修正後のコード

field :items, [Example::Types::ItemType], null: false,
      description: 'Fetches items with optional filters.' do
  argument :category, String, required: false,
            description: 'カテゴリー(例:書籍、雑貨)'
  argument :search_key, String, required: false,
            description: '検索キーワード'
end

参考

https://graphql-ruby.org/

https://graphql.org/

https://zenn.dev/igz0/articles/3fc43a7c02d9b9

Discussion