Created
October 14, 2017 22:51
-
-
Save spencercwood/4ac1190580147c86be36f74da8e4cfb8 to your computer and use it in GitHub Desktop.
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
const config = require('./config'); | |
const fetch = require('node-fetch'); | |
const querystring = require('querystring'); | |
module.exports = { | |
get, | |
post, | |
put, | |
delete: httpDelete, // function name can't be 'delete' | |
fetchJsonWithAuth, | |
fetchWithAuth, | |
}; | |
function get(uri, queryParams) { | |
return fetchJsonWithAuth( | |
uri + '?' + querystring.stringify(queryParams), | |
{method: 'GET'} | |
); | |
} | |
function post(uri, body = {}) { | |
return fetchJsonWithAuth(uri, { | |
method: 'POST', | |
body: JSON.stringify(body), | |
headers: {'Content-Type': 'application/json'}, | |
}); | |
} | |
function put(uri, body) { | |
return fetchJsonWithAuth(uri, { | |
method: 'PUT', | |
body: JSON.stringify(body), | |
headers: {'Content-Type': 'application/json'}, | |
}); | |
} | |
function httpDelete(uri, queryParams) { | |
return fetchJsonWithAuth( | |
uri + '?' + querystring.stringify(queryParams), | |
{method: 'DELETE'} | |
); | |
} | |
function fetchJsonWithAuth(uri, options = {}) { | |
if (!('headers' in options)) { | |
options.headers = {}; | |
} | |
if (!('Accept') in options.headers) { | |
options.headers.Accept = 'application/json'; | |
} | |
return fetchWithAuth(uri, options) | |
.then((response) => response.text()) | |
.then((text) => { | |
try { | |
return JSON.parse(text); | |
} catch (error) { | |
return text; | |
} | |
}); | |
} | |
function fetchWithAuth(uri, options = {}) { | |
if (!('headers' in options)) { | |
options.headers = {}; | |
} | |
options.headers['X-API-TOKEN'] = config.apiToken; | |
return fetch(config.baseUrl + uri, options) | |
.then(_throwOnBadStatusCode); | |
} | |
function _throwOnBadStatusCode(response) { | |
if (!response.ok) { | |
return response.text() | |
.then((text) => { | |
throw new Error(text); | |
}); | |
} else { | |
return response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment