Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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