Skip to content

Instantly share code, notes, and snippets.

@mul14
Last active November 21, 2020 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mul14/ecbd2b3dfd16c7236ae59f04dbae7add to your computer and use it in GitHub Desktop.
Save mul14/ecbd2b3dfd16c7236ae59f04dbae7add to your computer and use it in GitHub Desktop.
Simple GraphQL Client for web browser
function graphql_query(endpoint, query, variables = {}, token = null) {
return new Promise((resolve, reject) => {
const headers = {
'Content-Type': 'application/json',
}
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
fetch(endpoint, {
method: 'post',
headers,
body: JSON.stringify({
query,
variables,
}),
})
.then(response => response.json())
.then(json => resolve(json))
.catch(e => reject(e))
})
}
<!-- Usage example -->
<script src="graphql_query.js"></script>
<script>
const query = `query {
posts {
data {
id
title
}
}
}`;
graphql_query('https://graphqlzero.almansi.me/api', query)
.then(response => {
console.log(response)
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment