2

在我的 gatsby 项目中,我gatsby-node.js导出了两个 Bound Action Creator:onCreateNode 和 createPages。通常这些运行正常 - 当 onCreateNode 运行时,我使用一些现有节点来创建我想要的节点,然后 createPages 使用其中一些节点来创建页面。

但是,有时gatsby develop在终端运行时,我得到:

GraphQLError: Cannot query field "allBusiness" on type "RootQueryType". Did you mean "allBusinessesJson"?

TypeError: Cannot read property 'published_issues' of undefined

allBusiness是在 createNode 中创建的节点,并且published_issues是使用 allMarkdownRemark 进行查询的 graphql 别名(请参阅下面的完整代码)。

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

我无法确定 createPages Bound Action Creator 是异步的,而 onCreateNode 不是这样的问题。

gatsby-node.js代码:

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
4

0 回答 0