【问题标题】:Call a different REST endpoint per Gatsby Page每个 Gatsby 页面调用不同的 REST 端点
【发布时间】: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 } }

标签: rest graphql gatsby


【解决方案1】:

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

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

【讨论】:

  • 为什么不使用 context 传递给 resolve: async (source, args, context, info) - 它应该包含 locale - 不使用参数/参数?
  • 这样做有什么好处?
  • 不多,查询中不需要locale,查询和代码更简洁一些
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
相关资源
最近更新 更多