DEV Community

Phil Hughes
Phil Hughes

Posted on

Apollo and external services

Have you ever wanted to use GraphQL and Apollo but still wanted to access some external or older API?

Well you can! And it is super easy to do.

First lets setup our Apollo client

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';

const client = new ApolloClient({
  url: URL_TO_GRAPHQL,
  cache: new InMemoryCache(),
});
Enter fullscreen mode Exit fullscreen mode

Now this is where things get interesting. In older versions of Apollo you would use apollo-link-state which would allow you to access client data through the GraphQL queries. However, that has since been merged into Apollo Client (https://www.apollographql.com/docs/react/essentials/local-state/) 🎉

What this allows you to do is use the @client directive in queries to access locally cached data.

query {
  someLocalData @client
}
Enter fullscreen mode Exit fullscreen mode

Now that we know that we query local data through our GraphQL queries we can take our Apollo client code and add an extra property to create some local queries.

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';

const client = new ApolloClient({
  url: URL_TO_GRAPHQL,
  cache: new InMemoryCache(),
  resolvers: {
    Query: {
      oldApi() {
        return fetch('https://old.api.com/get/old/data')
          .then(r => r.json());
      },
    },
  }
});
Enter fullscreen mode Exit fullscreen mode

The resolvers: { Query {...} } part is the most important part of this. This tells Apollo that whenever it sees a @client directive in the query then to use our local resolvers for this instead of posting them to the API endpoint.

With the resolvers setup we can now create a query that looks something like:

query {
  oldApi @client {
    id
    text
  }
}
Enter fullscreen mode Exit fullscreen mode

But what uses does this actually have? Some examples:

  • Use a new GraphQL API for newer data but still access the old API
  • Create mutations that save data to an old internal API.

Top comments (0)