Skip to content

Instantly share code, notes, and snippets.

@jacobparis
Created April 17, 2019 18:25
Show Gist options
  • Save jacobparis/0e9f6787d5510f65a066fc85369bfeeb to your computer and use it in GitHub Desktop.
Save jacobparis/0e9f6787d5510f65a066fc85369bfeeb to your computer and use it in GitHub Desktop.
apiservice.js
const host = "http://localhost:3000/api/";
export default class APIService {
constructor() {
this.headers = {};
}
get(endpoint) {
return this.makeRequest({ method: "GET", url: host + endpoint, headers: this.headers})
}
post(endpoint, body) {
return this.makeRequest({ method: "POST", url: host + endpoint, headers: this.headers, params: body});
}
put(endpoint, body) {
return this.makeRequest({ method: "PUT", url: host + endpoint, headers: this.headers, params: body});
}
delete(endpoint, body) {
return this.makeRequest({ method: "DELETE", url: host + endpoint, headers: this.headers, params: body});
}
secure(token) {
this.headers.Authorization = token;
return this;
}
makeRequest(options) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(options.method, options.url);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject({
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = reject;
if (options.headers) {
Object.keys(options.headers).forEach((key) => {
console.log(key, options.headers[key]);
xhr.setRequestHeader(key, options.headers[key]);
});
}
if (options.method == "GET") {
// We'll need to stringify if we've been given an object
// If we have a string, this is skipped.
if (options.params && typeof options.params === 'object') {
options.params = Object.keys(options.params).map((key) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(options.params[key]);
}).join('&');
}
}
if (options.method == "POST" || options.method == "PUT" || options.method == "DELETE") {
xhr.setRequestHeader("Content-Type", "application/json");
if (options.params && typeof options.params === 'object') {
options.params = JSON.stringify(options.params);
}
}
xhr.send(options.params);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment