How to work with both mocked graphql API and an externally served GraphQL endpoint

Viewed 46

I'm hoping to hear some inputs from the experts here. I'm currently working on NextJS project and my graphql is running on mocked data which is setup in another repo. and now that the backend is built by other devs were slowly moving away from mocked data to the real ones. They've given me an endpoint to the backend where I'm supposed to be querying data. So the goal is to make both mocked graphql data and the real data in backend work side by side at least until we fully removed mocked data. So far saw 2 ways of doing it, but I was looking for a way where I could still use hooks like useQuery and useMutation

Way #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));

Way #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)
}
1 Answers

Pseudo code:

  1. Query the real data first
  2. check if its empty, if it is, query the mock data.
  3. If both are empty, then it's really an empty result set.

You can write a wrapper around the hooks you use that does this for you so you don't have to repeat yourself in every component. When you're ready to remove the mocked data you just remove the check for the second. data set.

This is a common technique when switching to a new database.

Related