メンチカツ

ロースカツが好きです

【メモ】graphql-codegenの「AggregateError: GraphQL Document Validation failed」を解決する

タイトルの通りなんだけど

graphql-codegen のValidationエラーの原因がいつもよくわからない

$ yarn graphql-codegen

  ...

  ❯ Generate outputs
    ❯ Generate /hoge/fuga/frontend/src/pages/User/graphql.ts
      ✔ Load GraphQL schemas
      ✔ Load GraphQL documents
      ✖ Generate
        → GraphQL Document Validation failed with 1 errors


 Found 1 error

  ✖ /hoge/fuga/frontend/src/pages/User/graphql.ts
    AggregateError: GraphQL Document Validation failed with 1 errors
        at Object.checkValidationErrors (/hoge/fuga/frontend/node_modules/@graphql-codegen/core/node_modules/@graphql-tools/utils/index.js:962:15)

        ...

いやーいくらなんでも抽象的すぎん?

というわけでエラーの詳細を知るために、 @graphql-tools/utils/index.js:962 の手前に console.table を仕込む

// @graphql-tools/utils/index.js:944目あたり

function checkValidationErrors(loadDocumentErrors) {
    if (loadDocumentErrors.length > 0) {
        const errors = [];
        for (const loadDocumentError of loadDocumentErrors) {
            for (const graphQLError of loadDocumentError.errors) {
                const error = new Error();
                error.name = 'GraphQLDocumentError';
                error.message = `${error.name}: ${graphQLError.message}`;
                error.stack = error.message;
                if (graphQLError.locations) {
                    for (const location of graphQLError.locations) {
                        error.stack += `\n    at ${loadDocumentError.filePath}:${location.line}:${location.column}`;
                    }
                }
                console.table(error) // コレを追加
                errors.push(error);
            }
        }
        throw new exports.AggregateError(errors, `GraphQL Document Validation failed with ${loadDocumentErrors.length} errors`);
    }
}

この状態で再実施するとエラーの詳細が表示されて

GraphQLDocumentError

あっ!なるほどな!となれると思います。