Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Gatsby JS节点并不总是正确创建以供createPages使用_Gatsby - Fatal编程技术网

Gatsby JS节点并不总是正确创建以供createPages使用

Gatsby JS节点并不总是正确创建以供createPages使用,gatsby,Gatsby,在我的盖茨比项目中,我有gatsby node.js导出两个绑定动作创建者:onCreateNode和createPages。通常这些运行正常-当onCreateNode运行时,我使用一些现有节点创建我想要的节点,然后createPages使用其中一些节点创建页面 然而,有时在终端中运行gatsby develope时,我会得到: GraphQLError:无法查询类型“RootQueryType”上的字段“allBusiness”。你是说“allBusinessesJson”吗? 及 Type

在我的盖茨比项目中,我有
gatsby node.js
导出两个绑定动作创建者:onCreateNode和createPages。通常这些运行正常-当onCreateNode运行时,我使用一些现有节点创建我想要的节点,然后createPages使用其中一些节点创建页面

然而,有时在终端中运行
gatsby develope
时,我会得到:

GraphQLError:无法查询类型“RootQueryType”上的字段“allBusiness”。你是说“allBusinessesJson”吗?

TypeError:无法读取未定义的属性“published\u issues”

allBusiness
是在createNode中创建的节点,
published\u issues
是使用allMarkdownRemark的查询的graphql别名(请参阅下面的完整代码)

但是,经常稍微更改
gatsby node.js
中的代码(例如添加控制台日志)将解决问题,并且项目将正确构建。这很好,尽管我已经接近生产阶段,而且Netlify中的预定构建(例如)显然并不总是有效

我无法确定createPages绑定的操作创建者是异步的,而onCreateNode不是异步的,这是否是一个问题

gatsby node.js
code:

const path = require('path');
const fs = require('fs');
const slugCreator = require('slug');
const rp = require('request-promise');
const jsonWriter = require('./gatsby-node-json-writer');
const dropRight = require('lodash/dropRight');


exports.onCreateNode = ({ node, boundActionCreators, getNode }) => {

  const { createNodeField, createNode } = boundActionCreators;
  const pathRegEx = /\/local-business-directory\//;
  let slug;
  // if(node.internal.type==='MarkdownRemark' && pathRegEx.test(node.id)){
  //   jsonWriter(node);
  // }

  if (node.internal.type === `AllDataJson`) {
    //place jsonWriter (with parameter of'node') here

    const { businesses } = node;
    businesses.forEach((business) => {
      business.id = slugCreator(business.company_name, { lower: true });
      business.parent = " ";
      business.children = [];
      business.internal = {};
      business.internal.contentDigest = business.company_name;
      business.internal.type = "Business";
      business.image = `${business.image}`;
      createNode(
        business
      )
    })


  }

  if (node.internal.type === `MarkdownRemark`) {
    const fileNode = getNode(node.parent);
    const parsedFilePath = path.parse(fileNode.relativePath);
    if (parsedFilePath.name !== `index` && parsedFilePath.dir !== ``) {
      slug = `/${parsedFilePath.dir}/${parsedFilePath.name}/`
    } else if (parsedFilePath.dir === ``) {
      slug = `/${parsedFilePath.name}/`
    } else {
      slug = `/${parsedFilePath.dir}/`
    }
    // Add slug as a field on the node.
    createNodeField({ node, name: `slug`, value: slug })
  }

  if (node.internal.type === "Business") {
    const nodeName = node.company_name;
    const slug = `/local-business-directory/${slugCreator(nodeName, { lower: true })}`;
    // Add slug as a field on the node.
    createNodeField({ node, name: `slug`, value: slug })
  }
}
;


exports.createPages = ({ graphql, boundActionCreators }) => {
  const { createPage } = boundActionCreators;

  return new Promise((resolve, reject) => {
    const publishedIssuePage = path.resolve("src/templates/published-issue.js");
    const advertiserPage = path.resolve("src/templates/advertiser/index.js");
    // Query for all markdown "nodes" and for the slug we previously created.
    resolve(
      graphql(
        `
        {
          advertisers: allBusiness {
            edges {
              node {
                id
                image
                fields {
                  slug
                }
              }
            }
          }
          published_issues: allMarkdownRemark(filter: {fileAbsolutePath: {regex: "/published-issues/"}}) {
            edges {
              node {
              id
                fields {
                  slug
                }
                frontmatter {
                  imageURL
                }
              }
            }
          }
        }
      `
      ).then(result => {
        if (result.errors) {
          console.log(result.errors);
          reject(result.errors)
        }

        // Create blog posts pages.
        result.data.published_issues.edges.forEach(edge => {
          const imageURLRegex = `/${edge.node.frontmatter.imageURL}/g`;
          createPage({
            path: edge.node.fields.slug, // required
            component: publishedIssuePage,
            context: {
              slug: edge.node.fields.slug,
              imageURLRegex,
            },
          })
        });

        result.data.advertisers.edges.forEach(edge => {
          const imageURLRegex = `/${edge.node.image}/`;
          console.log(imageURLRegex);
          createPage({
            path: edge.node.fields.slug, // required
            co    mponent: advertiserPage,
            context: {
              slug: edge.node.fields.slug,
              imageURLRegex
            },
          })
        });
        resolve();
      })
    )
  })
};
和生成日志:

[ { GraphQLError: Cannot query field "allBusiness" on type "RootQueryType". Did you mean "allBusinessesJson"?
      at Object.Field (/Users/Gridley123/bin/stiveslocal/node_modules/graphql/validation/rules/FieldsOnCorrectType.js:65:31)
      at Object.enter (/Users/Gridley123/bin/stiveslocal/node_modules/graphql/language/visitor.js:295:29)
      at Object.enter (/Users/Gridley123/bin/stiveslocal/node_modules/graphql/language/visitor.js:337:25)
      at visit (/Users/Gridley123/bin/stiveslocal/node_modules/graphql/language/visitor.js:227:26)
      at visitUsingRules (/Users/Gridley123/bin/stiveslocal/node_modules/graphql/validation/validate.js:75:22)
      at validate (/Users/Gridley123/bin/stiveslocal/node_modules/graphql/validation/validate.js:60:10)
      at /Users/Gridley123/bin/stiveslocal/node_modules/graphql/graphql.js:69:51
      at Promise._execute (/usr/local/lib/node_modules/gatsby/node_modules/bluebird/js/release/debuggability.js:303:9)
      at Promise._resolveFromExecutor (/usr/local/lib/node_modules/gatsby/node_modules/bluebird/js/release/promise.js:483:18)
      at new Promise (/usr/local/lib/node_modules/gatsby/node_modules/bluebird/js/release/promise.js:79:10)
      at graphqlImpl (/Users/Gridley123/bin/stiveslocal/node_modules/graphql/graphql.js:59:10)
      at graphql (/Users/Gridley123/bin/stiveslocal/node_modules/graphql/graphql.js:48:227)
      at graphqlRunner (/Users/Gridley123/bin/stiveslocal/node_modules/gatsby/dist/bootstrap/index.js:368:22)
      at Promise (/Users/Gridley123/bin/stiveslocal/gatsby-node.js:127:7)
      at Promise._execute (/usr/local/lib/node_modules/gatsby/node_modules/bluebird/js/release/debuggability.js:303:9)
      at Promise._resolveFromExecutor (/usr/local/lib/node_modules/gatsby/node_modules/bluebird/js/release/promise.js:483:18)
      at new Promise (/usr/local/lib/node_modules/gatsby/node_modules/bluebird/js/release/promise.js:79:10)
      at Object.exports.createPages (/Users/Gridley123/bin/stiveslocal/gatsby-node.js:122:10)
      at runAPI (/Users/Gridley123/bin/stiveslocal/node_modules/gatsby/dist/utils/api-runner-node.js:104:36)
      at /Users/Gridley123/bin/stiveslocal/node_modules/gatsby/dist/utils/api-runner-node.js:178:33
      at /Users/Gridley123/bin/stiveslocal/node_modules/async/internal/map.js:27:9
      at replenish (/Users/Gridley123/bin/stiveslocal/node_modules/async/internal/eachOfLimit.js:64:17)
      at iterateeCallback (/Users/Gridley123/bin/stiveslocal/node_modules/async/internal/eachOfLimit.js:49:17)
      at /Users/Gridley123/bin/stiveslocal/node_modules/async/internal/onlyOnce.js:12:16
      at /Users/Gridley123/bin/stiveslocal/node_modules/async/internal/map.js:29:13
      at tryCatcher (/Users/Gridley123/bin/stiveslocal/node_modules/bluebird/js/release/util.js:16:23)
      at Promise.successAdapter (/Users/Gridley123/bin/stiveslocal/node_modules/bluebird/js/release/nodeify.js:23:30)
      at Promise._settlePromise (/Users/Gridley123/bin/stiveslocal/node_modules/bluebird/js/release/promise.js:566:21)
    message: 'Cannot query field "allBusiness" on type "RootQueryType". Did you mean "allBusinessesJson"?',
    locations: [ [Object] ],
    path: undefined } ]
error Plugin default-site-plugin returned an error


  TypeError: Cannot read property 'published_issues' of undefined

  - gatsby-node.js:163 graphql.then.result
    /Users/Gridley123/bin/stiveslocal/gatsby-node.js:163:20

  - util.js:16 tryCatcher
    [lib]/[gatsby]/[bluebird]/js/release/util.js:16:23

  - promise.js:512 Promise._settlePromiseFromHandler
    [lib]/[gatsby]/[bluebird]/js/release/promise.js:512:31

  - promise.js:569 Promise._settlePromise
    [lib]/[gatsby]/[bluebird]/js/release/promise.js:569:18

  - promise.js:606 Promise._settlePromiseCtx
    [lib]/[gatsby]/[bluebird]/js/release/promise.js:606:10

  - async.js:138 Async._drainQueue
    [lib]/[gatsby]/[bluebird]/js/release/async.js:138:12

  - async.js:143 Async._drainQueues
    [lib]/[gatsby]/[bluebird]/js/release/async.js:143:10

  - async.js:17 Immediate.Async.drainQueues
    [lib]/[gatsby]/[bluebird]/js/release/async.js:17:14