gpt4 book ai didi

javascript - 如何在 gatsby 的 graphql 查询中使用正则表达式

转载 作者:行者123 更新时间:2023-12-04 17:18:41 25 4
gpt4 key购买 nike

我已经为我的个人产品页面创建了页面查询。

它确实针对单个产品,我想添加一个过滤器,如果多个产品具有相似的 SKU,我需要向它们展示。查询在 Grphiql 界面中工作正常,但在代码中它只显示一个 Node 。

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 中只产生一个 Node ,尽管它在 graphiql 中返回多个 Node

Gatsby 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 中的上下文中将 SKU 沿着 ID 传递

最佳答案

除了您使用模板文字来保存动态正则表达式之外,您的解决方法应该可行。对于这种方法,我会尝试做类似的事情:

        context: {
id: node.id,
sku: new RegExp(String.raw `${node.sku}`, 'i'), //add other flags if needed
}

或者尝试:

new RegExp(node.sku, 'i').toString()

RegExp 构造函数应该为这个用例做一些小技巧来强制使用原始字符串(因为 GraphQL 中的比较需要用字符串值表示)。

关于javascript - 如何在 gatsby 的 graphql 查询中使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67579160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com