GraphQL中的复杂查询变量(通过Gatsby) [英] Complex query variables in GraphQL (via Gatsby)
问题描述
我正在gatsby-plugin-intl
的帮助下使用Gatsby构建本地化的静态网站.此插件将名为intl
的上下文变量添加到作为对象的页面(包括基于模板的页面):
I am building a localized static website using Gatsby, with the help of gatsby-plugin-intl
. This plugin adds a context variable named intl
to pages (including template-based pages), which is an object: https://github.com/wiziple/gatsby-plugin-intl/blob/master/src/gatsby-node.js#L27-L34
我想从页面查询中的上下文访问intl.language
变量.这是我现阶段(失败)的代码:
I would like to access the intl.language
variable from the context within a page query. This is my (failing) code at this stage:
query($slug: String!, $intl: String) {
contentfulPerson(slug: {eq: $slug}, node_locale: {eq: $intl.language}) {
name
}
}
Contentful是我使用的无头CMS,我希望从该CMS中以正确的语言环境获取数据.
Contentful is the headless CMS I use and from which I would like to fetch data in the correct locale.
显然,此代码有两个问题:$intl
不是字符串,并且$intl.language
在语法上不正确.但是我不知道如何解决这两个问题.
Obviously this code has two problems: $intl
is not a string, and $intl.language
is not syntactically correct. But I don't know how to fix either problem.
我想我可以派生插件或在自己的gatsby-node.js
中做一些事情,以使该语言在上下文中作为顶级变量可用,但是我很想知道是否有办法直接地.
Gatsby文档说查询变量可能很复杂( https://www.gatsbyjs .org/docs/graphql-reference/#query-variables ),但在它们提供的示例中,它们没有显示类型的定义方式或如何在这些变量中访问属性.
I guess I could either fork the plugin or do something in my own gatsby-node.js
to make the language available as a top-level variable in the context, but I'm interested to know if there is a way to do it directly.
The Gatsby docs say that query variables can be complex (https://www.gatsbyjs.org/docs/graphql-reference/#query-variables) but in the example they provide, they don't show how the types are defined or how to access a property within these variables.
我尝试使用以下代码将语言移至gatsby-node.js
中的顶级上下文变量:
EDIT : I tried moving the language to a top-level context variable in my gatsby-node.js
using this code:
exports.onCreatePage = ({page, actions}) => {
const { createPage, deletePage } = actions
deletePage(page)
createPage({
...page,
context: {
...page.context,
language: page.context.intl.language
}
})
}
但是程序内存不足(即使增加max_old_space_size
时)
but the program runs out of memory (even when increasing max_old_space_size
)
推荐答案
您可以通过以下操作将language
字段移至顶级上下文:
You can move the language
field to a top-level context by doing this:
exports.onCreatePage = ({ page, actions }) => {
const { createPage, deletePage } = actions
const oldPage = Object.assign({}, page)
page.context.language = page.context.intl.language;
if (page.context.language !== oldPage.context.language) {
// Replace new page with old page
deletePage(oldPage)
createPage(page)
}
}
检查字段是否已更改避免了无限循环.
Checking if the field has changed avoids the infinity loop.
这篇关于GraphQL中的复杂查询变量(通过Gatsby)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!