Skip to content

Instantly share code, notes, and snippets.

@paulcollett
Last active May 4, 2020 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulcollett/07e1eb1d8dac4de2e42965b673faf95f to your computer and use it in GitHub Desktop.
Save paulcollett/07e1eb1d8dac4de2e42965b673faf95f to your computer and use it in GitHub Desktop.
small filesize graphql request, returns promise
/**
* small graphql request that adheres to the POST JSON spec, returns promise
* @param {string} endpoint graphql url
* @param {string} query graphql query / mutation
* @param {object=} variables object of variables, optional
* @param {object=} headers object of headers, optional
* @return {Promise.<object, Error>} promise with json data
* @example
graphQlRequest('https://domain/endpoint', 'query { hero { name } }')
*/
const graphQlRequest = (endpoint, query, variables, headers = { 'content-type': 'application/json' }) => {
const body = JSON.stringify({
query,
variables
})
const generateError = (msg = 'Server Response Error') => {
throw new Error(msg)
}
return fetch(endpoint, { method: 'post', headers, body })
.catch(() => generateError('Request Error'))
.then(res => res.json().catch(() => generateError()))
.then(res => {
if (res.errors || typeof res.data !== 'object') {
generateError(res.errors ? res.errors[0].message : undefined)
}
return res.data
})
}
export default graphQlRequest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment