0

我在 gatsby-node.js 中创建了一个函数,该函数在用户和位置之间创建链接,并根据降价文件中的信息将它们发布到正确的路径。

现在,我有一个本地 data.json,其中包含我需要集成到此功能中的每个用户的调查数据。

我需要从 data.json 导入数据并检查 - 当前处理的用户页面是否在 data.json 中有匹配的电子邮件地址,然后将推荐添加到输出数据中。我正在努力寻找如何将此逻辑集成到现有功能中的方法。

节点.js

const path = require("path");
const { createFilePath } = require("gatsby-source-filesystem");
const data = require("src/data/data.json");

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

    return graphql(`
        {
            allMarkdownRemark(limit: 1000) {
                edges {
                    node {
                        id
                        fields {
                            slug
                        }
                        frontmatter {
                            templateKey
                            title
                            location
                        }
                    }
                }
            }
        }
    `).then(result => {
        if (result.errors) {
            result.errors.forEach(e => console.error(e.toString()));
            return Promise.reject(result.errors);
        }

        const edges = result.data.allMarkdownRemark.edges;

        edges.forEach(edge => {
            const id = edge.node.id;
            const title = edge.node.frontmatter.title;
            const location = edge.node.frontmatter.location || null;
            createPage({
                path: edge.node.fields.slug,
                component: path.resolve(
                    `src/templates/${String(
                        edge.node.frontmatter.templateKey,
                    )}.js`,
                ),
                // query variables are passed in via the context
                context: {
                    id,
                    title,
                    location,
                },
            });
        });
    });
};

exports.onCreateNode = ({ node, actions, getNode }) => {
    const { createNodeField } = actions;

    if (node.internal.type === `MarkdownRemark`) {
        const value = createFilePath({ node, getNode });
        createNodeField({
            name: `slug`,
            node,
            value,
        });
    }
};

JSON

[
  {
    "agreed": true,
    "email": "alex@test.com"
    "testimonials": [
      {
        "name": "Alex",
        "city": "Pedro",
        "state": "WA",
        "description": "Alex was very patient. He is one of the good guys!"
      }
    ]
  }
]
4

1 回答 1

0

您需要将电子邮件字段包含在 graphql 查询中,位于 markdown 文件的 frontmatter 属性中。从那里你可以data.find(u => u.email == edge.node.frontmatter.social_id)找到合适的用户,并在 createPage 的上下文中传递整个对象,或者只是推荐,你的调用。

于 2018-12-03T23:14:26.300 回答