【问题标题】:How to work with both mocked graphql API and an externally served GraphQL endpoint如何使用模拟的 graphql API 和外部服务的 GraphQL 端点
【发布时间】:2021-04-16 02:41:44
【问题描述】:

我希望在这里听到专家的一些意见。 我目前正在研究 NextJS 项目,我的 graphql 正在运行在另一个 repo 中设置的模拟数据。 现在后端是由其他开发人员构建的,正在慢慢地从模拟数据转向真实数据。 他们给了我一个后端的端点,我应该在其中查询数据。 因此,目标是至少在我们完全删除模拟数据之前,让模拟的 graphql 数据和后端的真实数据并行工作。 到目前为止,我看到了 2 种方法,但我一直在寻找一种方法,我仍然可以使用像 useQuery 和 useMutation 这样的钩子

方式#1

require('isomorphic-fetch');
fetch('https://graphql.api....', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: `
    query {
        popularBrands ( storefront:"bax-shop.nl", limit:10, page:1){
            totalCount
            items{id
            logo  
            name
            image
            }
          }
        }` 
    }),
})
.then(res => res.json())
.then(res => console.log(res.data));

方式#2

const client = new ApolloClient({
    uri: 'https://api.spacex.land/graphql/',
    cache: new InMemoryCache()
});
async function test () {
    const { data: Data } = await client.query({
        query: gql`
          query GetLaunches {
            launchesPast(limit: 10) {
              id
              mission_name
              launch_date_local
              launch_site {
                site_name_long
              }
              links {
                article_link
                video_link
                mission_patch
              }
              rocket {
                rocket_name
              }
            }
          }
        `
      });
      console.log(Data)
}

【问题讨论】:

    标签: graphql next.js react-apollo


    【解决方案1】:

    伪代码:

    1. 先查询真实数据
    2. 检查是否为空,如果为空,则查询mock数据。
    3. 如果两者都是空的,那么它确实是一个空结果集。

    您可以为您使用的钩子编写一个包装器来为您执行此操作,这样您就不必在每个组件中重复自己。当您准备好删除模拟数据时,您只需删除第二个检查。数据集。

    这是切换到新数据库时的常用技术。

    【讨论】:

      猜你喜欢
      • 2017-07-01
      • 2017-08-08
      • 2020-10-25
      • 2019-04-17
      • 2019-06-19
      • 2019-06-22
      • 1970-01-01
      • 2018-11-28
      • 2016-04-15
      相关资源
      最近更新 更多