【发布时间】:2021-08-07 06:35:24
【问题描述】:
我已经为我的个人产品页面创建了页面查询。
它确实适用于单个产品,我想添加一个过滤器,如果多个产品具有相似的 SKU,我需要向它们展示。查询在 Grphiql 界面中运行良好,但在代码中它只显示一个节点。
Grahiql 查询
query ($id: String, $sku: String) {
productsCsv(id: {eq: $id}) {
id
name
productCategory
sizes
sku
stock
instock
description
colors
templateKey
price
discount
fields {
slug
}
}
allProductsCsv(filter: {sku: {regex: $sku}, instock: {eq: "TRUE"}}) {
edges {
node {
id
instock
stock
sku
colors
sizes
}
}
}
}
在查询变量部分,我正在传递这样的变量
{
"sku": "/DW20DK18/"
}
allProductCsv 在 gatsby 中只产生一个节点,尽管它在 graphiql 中返回多个节点
盖茨比-node.js
const { createFilePath } = require("gatsby-source-filesystem")
const path = require(`path`)
const onCreateNode = ({node,actions,getNode}) => {
const {createNodeField} = actions
if(node.internal.type === `MarkdownRemark`) {
const value = createFilePath({node, getNode})
createNodeField({
name:`slug`,
node,
value
})
}
if(node.internal.type === `ProductsCsv`) {
const value = node.name
const processedSlug = value.replace(/\s+/g, '-').toLowerCase();
createNodeField({
name:`slug`,
node,
value: processedSlug
})
}
}
const createPages = async ({actions,graphql}) => {
const {createPage} = actions
const result = await graphql(`
{
allMarkdownRemark {
edges {
node {
frontmatter {
productColors
age
}
}
}
}
allProductsCsv {
edges {
node {
id
sku
fields{
slug
}
templateKey
productCategory
}
}
}
}
`)
if(result.errors){
console.error(result.errors)
}
result.data.allProductsCsv.edges.forEach(({ node }) => {
console.log(node.productCategory)
createPage({
path: `${String(node.productCategory)}/${node.fields.slug}`,
component: path.resolve(
`src/templates/${String(node.templateKey)}.js`
),
context: {
id: node.id,
sku: `/${node.sku}/`.toString(). //Passing SKU from Here
}
})
})
}
module.exports = {
/*
1. function for how to create page
2. On create node
*/
onCreateNode,
createPages
};
我在 gatsby-node.js 的 Context 中沿 ID 一侧传递 SKU
【问题讨论】:
标签: javascript node.js graphql e-commerce gatsby