Skip to content

Instantly share code, notes, and snippets.

@spencercwood
Created October 14, 2017 22:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spencercwood/4ac1190580147c86be36f74da8e4cfb8 to your computer and use it in GitHub Desktop.
Save spencercwood/4ac1190580147c86be36f74da8e4cfb8 to your computer and use it in GitHub Desktop.
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