Skip to content

Instantly share code, notes, and snippets.

@balazsorban44
Created September 2, 2021 10:33
Show Gist options
  • Save balazsorban44/c3eb0f8921e8ce04ccb50e076b4a87f9 to your computer and use it in GitHub Desktop.
Save balazsorban44/c3eb0f8921e8ce04ccb50e076b4a87f9 to your computer and use it in GitHub Desktop.
Simple GraphQL client
export default function GQLClient(params) {
return {
async request(query, variables) {
const token = params.token ?? (await getToken(params.client))
const res = await fetch(params.url, {
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : undefined),
},
method: "POST",
body: JSON.stringify({ query, variables }),
})
const json = await res.json()
if (json.errors) {
params.onError({
errors: json.errors,
message: json.errors.map((e) => e.message).join(", "),
query,
variables,
})
return
}
return json.data
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment