Search code examples
graphqlapollo-clientgraphiql

Use Apollo Client or Isomorphic Fetch with GraphiQL


I am trying to integrate the GraphiQL IDE into my website and am wondering if I can get some advice on whether I would be best using the Apollo Client that the rest of the site uses or using Isomorphic Fetch as recommended in the documentation.

If I use the Apollo Client then I only have one connection to worry about and don't have to think about ensuring authentication is correct but the code is more complex.

I have this code working for the fetcher function, but so far it only works with queries and to my understanding would need a fair amount of work to work with mutations as well.

graphQlFetcher = (params) => {
    return this.props.client.query({
        query: gql`
            ${params.query}
        `
    }).then(function(result) {
        return result;
    });
}

Alternatively there is the isomorphic fetch approach, but for this to work I need to get the authentication token first and I am not good enough with promises to make this work. Not working code:

import { Auth } from 'aws-amplify';

getToken = async () => {
    const session = await Auth.currentSession();
    return session.accessToken.jwtToken;
}

graphQLFetcher = (graphQLParams) => {
    return getToken().then(function(token) {
        fetch(window.location.origin + '/graphql', {
            method: 'post',
            headers: { 
                  'Content-Type': 'application/json',
                  "Authorization": token
              },
            body: JSON.stringify(graphQLParams),
          }).then(response => response.json());
    })
}

Appreciate that there are two possible ways to solve this problem and that it is as much a design question as a technical one but hoping that someone can help me out.


Solution

  • The first one is fine, but you have some excess syntax on there. This is what I use:

    params => client.query({ ...params, query: gql(params.query) });