Last active
May 12, 2020 19:05
-
-
Save lopezjurip/0f2124ade253e05ab36630c5fbb247f3 to your computer and use it in GitHub Desktop.
Quickstart Apollo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { | |
// ... | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | |
} | |
} | |
`; | |
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