个性化定制Gatsby / Contentful架构

4

我试图为一个Contentful数据源添加 createSchemaCustomization,但这个数据源可能没有我感兴趣的字段,所以Gatsby无法推断类型。

我已经创建了自定义设置,以便我的模板查询不会出错,但如果有条目,它也没有被选中。我确定我可能没有正确设置自定义配置。以下是我拥有的内容(@infer标志似乎也没有什么作用):

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions;
  const typeDefs = `
    type ContentfulUniversalProduct implements Node @infer {
      datesAndPricesSnippets: [DatesAndPricesSnippet]
    }
    type DatesAndPricesSnippet implements Node @infer {
      id: String
      title: String
      icon: String
      iconColor: String
      body: WithChildMarkdownRemark
    }
    type WithChildMarkdownRemark implements Node @infer {
      childMarkdownRemark: MarkdownRemark
    }
  `;
  createTypes(typeDefs);
};

我的查询。

如果Contentful中有datesAndPricesSnippets,且我没有进行上述的schemaCustomization,则此查询有效。

如果我进行了自定义操作,那么无论内容是否在Contentful中,此查询的输出结果都是null

export const query = graphql`
  query($slug: String!, $id: String!) {
    contentfulUniversalProduct {
      datesAndPricesSnippets {
        id
        title
        body {
          childMarkdownRemark {
            html
          }
        }
        icon
        iconColor
      }
    }
  }
`
2个回答

4

我遇到了一个类似的问题,以下内容对我有所帮助:

  1. 安装gatsby-plugin-schema-snapshot
  2. 生成schema.gql文件,GATSBY_UPDATE_SCHEMA_SNAPSHOT=y yarn develop 对我很有用
  3. 观察schema.gql文件,您使用createTypes添加的更改将显示出来

在我的情况下,添加@link调用可以帮助返回节点而不是null:

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions
  const typeDefs = `
    type ContentfulThing implements Node {
      fieldWithModules: [SomeBigUnion] @link(by: "id", from: "fieldWithModules___NODE")
    }
  `
  createTypes(typeDefs)
}

1
如果您将GATSBY_UPDATE_SCHEMA_SNAPSHOT=y(或任何您想要的内容)添加到.env.development.env.production中,则无需将其添加到#2命令中。 - ProGrammar

0

使用gatsby-plugin-schema-snapshot(来自另一个答案)实际上在我尝试处理来自Contentful的Markdown内容丢失的情况时并没有起作用。

然而,有一种通过actions访问的方法可以生成更准确的类型定义文件。然后,如果您直接将相关类型复制到createSchemaCustomization中定义的typeDefs中,它似乎可以按预期工作 - 无论Markdown内容是否存在。

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions;
 
  // This is what generates the type defs
  actions.printTypeDefinitions({path: './typeDefs.txt'});

  const typeDefs = `
    // Your type defs from the generated file here
    // (just the ones you've been having issues with)
  `;
  createTypes(typeDefs)
};

希望这能帮到你!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接