Skip to content

Instantly share code, notes, and snippets.

@kn9ts
Last active December 4, 2018 08:43
Show Gist options
  • Save kn9ts/414ae6a2a50dffd0c38551261ac397c1 to your computer and use it in GitHub Desktop.
Save kn9ts/414ae6a2a50dffd0c38551261ac397c1 to your computer and use it in GitHub Desktop.
makeHTTPRequest.js
import queryparams from 'query-params';
export default (method, targetedResource, { headers, pathVariables, params, body }) => {
if (pathVariables) {
Object.keys(pathVariables).forEach((key) => {
targetedResource = targetedResource.replace(`{${key}}`, pathVariables[key]);
});
}
if (params) targetedResource += `?${queryparams.encode(params)}`;
if (body) body = typeof body !== 'string' ? JSON.stringify(body): body;
return new Promise((resolve, reject) => {
// headers.Accept = [headers.Accept, 'application/json'].join(';');
const request = new XMLHttpRequest();
request.open(method, targetedResource, true);
if (headers && Object.keys(headers).length) {
Object.keys(headers).forEach((key) => {
request.setRequestHeader(key, headers[key]);
});
}
request.onload = () => {
const { status, statusText, responseText, readyState } = request;
let response;
try {
response = responseText !== '' ? JSON.parse(responseText) : {};
} catch (e) {
reject(e);
}
if (readyState === request.DONE && status >= 400) {
reject({ status, statusText, response });
return;
}
if (readyState === request.DONE && status >= 200 && status < 300) {
resolve({ status, statusText, response });
return;
}
reject({ status, statusText, response });
};
request.onerror = (error) => {
// eslint-disable-next-line
const { status, statusText, responseText } = request;
const response = responseText !== '' ? JSON.parse(responseText) : {};
reject({ status, statusText, response, error });
};
(body ? request.send(body) : request.send());
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment