【发布时间】:2019-10-01 18:33:40
【问题描述】:
我正在编写一个 Gatsby 插件来使用返回 HTML 的服务。相关端点会根据我正在创建的每个 Gatsby 页面进行更改。具体来说,这是基于语言环境-
-
homepage.com需要打电话给service.com/en -
homepage.es需要打电话给service.com/es
等等
我可以将语言环境从我的项目的 gatsby-node.js 传递到我的上下文中,这使它在我的页面的 index.js 和 GraphQL 查询中可用,但我不知道如何在插件中捕获该变量。
// project/gatsby-node.js
export.createPages = () => {Locales.forEach(locale => {
createPage({
component: myComponent.js,
context: {
locale: locale
},
})
})
// project/page.js
export default (props) => {
return (
<div dangerouslySetInnerHTML={{__html: props.data.header.innerHtml}}></div>
);
}
export const query = graphql`
query {
header(locale: $locale) { // my understanding is that this should pass it to the GraphQL query
innerHtml
}
}`
// plugin/gatsby-node.js
exports.sourceNodes = async ({ boundActionCreators }, configOptions) => {
const { createNode } = boundActionCreators;
const fetchHtml = () => axios.get(configOptions.htmlServerUrl); // I need to append to the path here
// await for results
const res = await fetchHtml();
const htmlNode = {
id: "html",
internal: {
type: `html`
},
innerHtml: res.data,
};
return createNode(htmlNode);
}
我听说我需要 REST 服务上的批量端点,然后我可以过滤它。真的吗? 如何修改为每个不同页面发送的 HTTP 调用?
【问题讨论】:
-
我认为您需要获取所有语言环境,然后将
locale变量传递给 graphql 查询,而不是将locale传递给插件 -
也应该是
query GetLocale($locale: String) { header { innerHTML } }