DEV Community

Phil Hughes
Phil Hughes

Posted on

1

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay