Skip to content

Instantly share code, notes, and snippets.

@stubailo
Last active December 1, 2018 15:54
Show Gist options
  • Save stubailo/d0b9f169c759094e6d3108921898696f to your computer and use it in GitHub Desktop.
Save stubailo/d0b9f169c759094e6d3108921898696f to your computer and use it in GitHub Desktop.
Call a GraphQL API with apollo-fetch
const { createApolloFetch } = require('apollo-fetch');
const fetch = createApolloFetch({
uri: 'https://1jzxrj179.lp.gql.zone/graphql',
});
fetch({
query: '{ posts { title }}',
}).then(res => {
console.log(res.data);
});
// You can also easily pass variables for dynamic arguments
fetch({
query: `query PostsForAuthor($id: Int!) {
author(id: $id) {
firstName
posts {
title
votes
}
}
}`,
variables: { id: 1 },
}).then(res => {
console.log(res.data);
});
@Ganesh1991
Copy link

How can we send a header or authorization parameters?

@scottwb
Copy link

scottwb commented Nov 17, 2018

For @Ganesh1991 or anyone else that ends up here, this where I ended up for an auth header (and should work for modifying the request too):

After the

const fetch = createApolloFetch({
  uri: 'https://1jzxrj179.lp.gql.zone/graphql',
});

add something like this:

fetch.use({ request, options }, next) => {
  if (!options.headers) {
    options.headers = {};
  }
  options.headers['authorization'] = 'your-auth-header-here';
  next();
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment