javascript - 如何确保在 Gatsby 中使用 createNode 的 graphql 查询始终存在属性

标签 javascript node.js graphql gatsby

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`)
    }
  })
}

最佳答案

Gatsby 跳过 null 值。

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

关于javascript - 如何确保在 Gatsby 中使用 createNode 的 graphql 查询始终存在属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507757/

相关文章:

javascript - 如何使用 GraphQL 突变减少请求数?

javascript - 如何正确使用 GraphQLList 和 GraphQLInterfaceType?

graphql - AWS AppSync GraphQL 订阅在事件上返回空值

javascript - 我应该在 React 组件中初始化一个空状态变量吗?

javascript - 使用正则表达式获取括号内的内容

javascript - knockout 组件选择选项

javascript - 将 javascript blob 变量下载为 mhtml

node.js - 如何实时重新加载 LoopBack 项目?

node.js - 将 nodejs/mongoose 部署到 heroku

javascript - 解析JSON数组nodejs