首页 > 解决方案 > 每个 Gatsby 页面调用不同的 REST 端点

问题描述

我正在编写一个 Gatsby 插件来使用 HTML 返回服务。相关端点会根据我正在创建的每个 Gatsby 页面进行更改。具体来说,这是基于语言环境-

等等

我可以将语言环境从我的项目传递到我的上下文中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 调用?

标签: restgraphqlgatsby

解决方案


我们使用自定义解析器解决了这个问题。我们构建了一个扩展查询语法的插件:

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)
}

推荐阅读