Skip to content

Instantly share code, notes, and snippets.

@lopezjurip
Last active May 12, 2020 19:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lopezjurip/0f2124ade253e05ab36630c5fbb247f3 to your computer and use it in GitHub Desktop.
Quickstart Apollo
import { ApolloClient } from "apollo-boost";
import { setContext } from "apollo-link-context";
import { InMemoryCache } from "apollo-cache-inmemory";
export default class APIClient {
constructor(context = {}, options = {}) {
this.context = context;
this.options = { fetchPolicy: "no-cache", ...options };
const authLink = setContext((_, context) => {
return {
headers: {
...context.headers,
[`Authorization`]: context.token ? `Bearer ${context.token}` : undefined,
},
};
});
this.apollo = new ApolloClient({
uri: 'http://localhost:8000/graphql',
link: authLink,
cache: new InMemoryCache(),
});
}
async query(query, variables = {}, context = {}) {
try {
return await this.apollo.query({
query,
variables,
context: { ...this.context, ...context },
...this.options,
});
} catch (error) {
// ...
}
}
async mutate(mutation, variables = {}, context = {}) {
try {
return await this.apollo.mutate({
mutation,
variables,
context: { ...this.context, ...context },
...this.options,
});
} catch (error) {
// ...
}
}
}
import gql from "graphql-tag"
import APIClient from "./apollo-quick-client";
const client = new APIClient();
const query = gql`
query($id: String!) {
item(id: $id) {
value
}
}
`;
const { data } = await client.query(query, { id: 1 });
console.log(data["item"]);
// Authenticated
const query = gql`
query {
viewer {
email
}
}
`;
const { data } = await client.query(query, {}, { token: "TOKEN" });
console.log(data["viewer"]);
// It is possible to use client as:
const client = new APIClient({ token: "TOKEN" });
const { data } = await client.query(query);
console.log(data["viewer"]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment