Last active
November 21, 2020 09:34
-
-
Save mul14/ecbd2b3dfd16c7236ae59f04dbae7add to your computer and use it in GitHub Desktop.
Simple GraphQL Client for web browser
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
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)) | |
}) | |
} |
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
<!-- 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