Last active
May 4, 2020 21:54
-
-
Save paulcollett/07e1eb1d8dac4de2e42965b673faf95f to your computer and use it in GitHub Desktop.
small filesize graphql request, returns promise
This file contains hidden or 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
/** | |
* 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