2021.03.19

GatsbyでContentfulのフィールドが正しく取れなくて困った話


Gatsby + Contentfulでブログを作り、いざ公開しようと思ってContentfulで作っていたテストデータを削除すると以下のエラーが。

ERROR #85923 GRAPHQL
There was an error in your GraphQL query:
Cannot query field "description" on type "ContentfulBlogPost".
If you don't expect "description" to exist on the type "ContentfulBlogPost" it is most likely a typo.
However, if you expect "description" to exist there are a couple of solutions to common problems:
- If you added a new data source and/or changed something inside gatsby-node.js/gatsby-config.js, please try a restart of your development server
- The field might be accessible in another subfield, please try your query in GraphiQL and use the GraphiQL explorer to see which fields you can query and
what shape they have
- You want to optionally use your field "description" and right now it is not used anywhere. Therefore Gatsby can't infer the type and add it to the
GraphQL schema. A quick fix is to add at least one entry with that field ("dummy content")
It is recommended to explicitly type your GraphQL schema if you want to use optional fields. This way you don't have to add the mentioned "dummy content".
Visit our docs to learn how you can define the schema for "ContentfulBlogPost":
https://www.gatsbyjs.org/docs/schema-customization/#creating-type-definitions
File: src/templates/blog-post.tsx:312:7
failed We've encountered an error: Minified React error #31; visit https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=GraphQLDocumentError%3A
%20GraphQLDocumentError%3A%20Cannot%20query%20field%20%22description%22%20on%20type%20%22ContentfulBlogPost%22.&args[]= for the full message or use the
non-minified dev environment for full errors and additional helpful warnings.

GraphQLでContentfulからBlogPostを取得する際に、Contentfulで定義されているはずのdescriptionフィールドが、GraphQLのスキーマでは定義されておらずエラーとなっていました。

原因

原因はgatsby-source-contentfulにありました。

プラグインの公式ページには以下のようにあります。

At the moment, fields that do not have at least one populated instance will not be created in the GraphQL schema.

意訳すると、

現時点では、少なくとも一つのインスタンス(コンテンツ)で使用されていないフィールドは、GraphQLのスキーマに作られません。

これはGitHubでも議論されている問題のようですが、まだ解決されていません。

対処

暫定的な対処法はすべてのフィールドを埋めたダミーコンテンツをつくることでしょうか。

ただし、非公開のコンテンツではGatsbyがContentfulからデータを引くことができないため、公開されたコンテンツである必要があります。ダミーコンテンツが実際のビルドでは生成されないようにQueryに気を配る必要があるでしょう。

個人的にはそのような対応をしたくなかったので、とりあえず使いたかったdescriptionはこの記事で適当に埋めました。