【发布时间】:2019-10-20 06:18:39
【问题描述】:
我在 GatsbyJS 的 GraphQL 查询中过滤项目时遇到问题。我想我可以在createPage 的context 部分创建键值对(如下面的currentDate 和minusFiveDays),然后将它们用作页面组件中的参数,但它似乎不起作用。
在gatsby-node.js:
const currentDate = moment().format('YYYY-MM-DD');
const minusFiveDays = moment()
.subtract(5, 'days')
.format('YYYY-MM-DD');
console.log('DATE', minusFiveDays); // this logs correctly
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.frontmatter.slug,
component: someContentTypeTemplate,
context: {
// Can the names passed in here be accessed in
// graphql queries, prefixed with a dollar sign?
currentDate: currentDate,
minusFiveDays: minusFiveDays,
},
});
});
在我的src/pages/someContentType.js 文件中:
// TODO: this query doesn't work. No matter what condition I try to use
// for $minusFiveDays, it doesn't affect the output. The query does work in
// graphiql when I hard-code a string there like "2018-11-01".
export const pageQuery = graphql`
query($minusFiveDays: Date) { // this is the key from the file above
allMarkdownRemark(
filter: {
frontmatter: {
content_type: { eq: "some_content_type" }
start_date: { ne: null, gte: $minusFiveDays }
}
}
sort: { order: ASC, fields: [frontmatter___start_date] }
) {
edges {
node {
id
frontmatter {
created_at
slug
title
start_date(formatString: "DD MMMM YYYY")
end_date
}
}
}
}
}
`;
即使我像这样对其进行硬编码,它也不起作用,因此上下文似乎没有被传递到组件的 GraphQL 查询中:
context: {
currentDate: currentDate,
minusFiveDays: "2018-11-01",
},
这确实在 GraphiQL 中工作:
{
allMarkdownRemark(filter: {frontmatter: {content_type: {eq: "some_content_type"}, start_date: {ne: null, gte: "2018-11-01"}}}, sort: {order: DESC, fields: [frontmatter___start_date]}) {
edges {
node {
id
frontmatter {
created_at
slug
title
start_date(formatString: "DD MMMM YYYY")
end_date
}
}
}
}
}
我认为我的语法一定是错误的,但是我是 GraphQL 和 Gatsby 的新手,并且没有错误消息。 编辑:当我将Date 更改为Date! 时出现错误消息:Variable "$minusFiveDays" of required type "Date!" was not provided.
【问题讨论】:
-
Date在someContentType.js中来自哪里? -
在上面最上面的sn-p的前两行中定义了。
-
对不起,我想我误解了。您是指参数中的
Date吗?我认为这告诉 graphql 它应该期待一个日期而不是字符串之类的东西。我还尝试Date!使其成为必填字段,但它显示“错误:未提供所需类型“日期!”的变量“$minusFiveDays”。它没有被传入。 -
会不会是您的矩格式
('YYYY-MM-DD')与您的 graphQl 格式"DD MMMM YYYY"不兼容? -
我不认为这是问题所在,因为当我对其进行硬编码时,它在 graphiql 中有效(例如:gist.github.com/j127/038d832291cf69fffc5b1b90557f10cd)。错误消息是未提供该变量。我尝试更改它以使格式匹配,但错误消息没有改变。