rest - 每个 Gatsby 页面调用不同的 REST 端点
问题描述
我正在编写一个 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 调用?
解决方案
我们使用自定义解析器解决了这个问题。我们构建了一个扩展查询语法的插件:
exports.createResolvers = ({ createResolvers }, configOptions) => {
createResolvers({
Query: {
[configOptions.name]: {
type: `String`,
args: {
locale: 'String'
},
resolve: async (source, args, context, info) => {
const {
htmlServerUrl,
defaultResponse
} = configOptions;
return axios
.get(`${htmlServerUrl}?args.locale`)
.then(response => response.data)
.catch(err => defaultResponse || "");
},
},
},
})
}
然后gatsby-config
看起来像这样:
{
resolve: "my-plugin",
options: {
htmlServerUrl: `http://my.html-service.com`,
name: "header"
}
}
最后,这在组件中使用:
query($locale: String) {
header(locale: $locale)
}
推荐阅读
- regex - 在 grep/pgrep 过滤器中不使用 -v 不是“x”或“y”?
- ansible - 如何使用 Ansible 从另一个列表中删除子列表
- php - 邮递员中的PHP服务器响应低于1000MS,但不是通过设备应用程序
- kubernetes - 如何指定 ServiceAccount 由 kubernetes python sdk 中的 config.load_incluster_config() 获取
- python - 我应该使用夹具来执行设置功能吗?
- python - StackingClassifier 导致“ValueError:输入形状错误”错误
- python - 使用 Python 将 ssh 客户端与 Paramiko 连接到 Dell idrac 失败键盘交互式身份验证
- java - 测试帐号中是否仅存在一个连字符
- java - 在 O(1) 中检查 LinkedHashMap 中 2 个不同键的顺序
- asp.net-core-mvc - 使用 OpenIDConnect 时如何注销 ClaimsIdentity 用户