【问题标题】:How can you ensure a property is always present for a graphql query using createNode in Gatsby如何确保在 Gatsby 中使用 createNode 的 graphql 查询始终存在属性
【发布时间】:2018-07-08 12:46:09
【问题描述】:

createNode 的值为 null 时不会创建字段。我们有一个短暂的数据馈送,有时会返回某些字段为空的对象,尽管这种情况很少见。

我们想使用这个查询,但是因为有时name 为空,gatsby 会删除它并导致这个查询出错。

{
  allMyType {
    edges {
      node {
        id
        name
      }
    }
  } 
}

有没有办法解决这个问题?

这段代码模拟了用例:

const crypto = require('crypto')
exports.createPages = ({ boundActionCreators, graphql }) => {
  const { createNode } = boundActionCreators
  // Simulate an ephemeral data source that sometimes doesn't have all properties set
  const data = {
    id: '1',
    name: Math.random() < 0.5 ? null : 'Paul Serby' 
  }
  createNode({
    ...data,
    id: data.id,
    children: [],
    parent: null,
    internal: {
      type: 'MyType',
      contentDigest: crypto
        .createHash(`md5`)
        .update(JSON.stringify(data))
        .digest(`hex`)
    }
  })
}

【问题讨论】:

    标签: javascript node.js graphql gatsby


    【解决方案1】:

    盖茨比跳过null 值。

    它从源数据构建架构并忽略空值,因此如果传入数据中的每个字段都为空或null,则不会创建该字段。 This issue 表明在某些情况下,稀疏填充的字段也可能会被忽略。如果您可以将该字段设置为空字符串而不是 null(可能在您的源插件中),这可能会提供一种解决方法。

    【讨论】:

      猜你喜欢
      • 2020-11-20
      • 2018-03-21
      • 2020-05-05
      • 2019-06-25
      • 2019-12-21
      • 2021-01-06
      • 2019-09-20
      • 2020-03-23
      • 2018-04-14
      相关资源
      最近更新 更多