【问题标题】:How to add JSON field to Gatsby sourceNode?如何将 JSON 字段添加到 Gatsby sourceNode?
【发布时间】:2020-08-15 20:26:32
【问题描述】:

在我的 API 中,我有带有动态模式的 layout 属性,所以我将其添加到 sourceNode 作为字符串化 JSON:

  for (const { path } of nodesList) {
    /* ... */

    const node = {
      id: createNodeId(`cms-${cmsNode.id}`),
      /* this prop */
      layout: JSON.stringify(layout),
      parent: null,
      children: [],
      internal: {
        content: JSON.stringify(cmsNode),
        type: 'CmsNode',
      },
    }
    node.internal.contentDigest = createContentDigest(node)
    createNode(node)
  }

如何自定义此字段以在查询级别解析 JSON,而不是页面组件中的 JSON.parse

【问题讨论】:

  • 使用 graphql 自定义 json 类型(文档)...不要字符串化

标签: javascript json graphql gatsby


【解决方案1】:

我应该添加自定义类型:

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions
  const typeDefs = `
    type CmsNode implements Node @dontInfer {
      id: ID!
      parent: Node
      children: [Node!]!
      ...
      layout: JSON
    }
  `
  createTypes(typeDefs)
}

createNode 期间不要对这个道具进行字符串化。

【讨论】:

    猜你喜欢
    • 2019-08-22
    • 2020-12-01
    • 2020-07-19
    • 1970-01-01
    • 2018-05-09
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    相关资源
    最近更新 更多