Skip to content

Instantly share code, notes, and snippets.

@ca0v
Created January 5, 2016 20:11
Show Gist options
  • Save ca0v/c2e4949b4e9fadef921b to your computer and use it in GitHub Desktop.
Save ca0v/c2e4949b4e9fadef921b to your computer and use it in GitHub Desktop.
REST Proxy
/**
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
*/
class Ajax {
constructor (public url) {
}
// Method that performs the ajax request
private ajax(method, args?, url = this.url) {
// Creating a promise
var promise = new Promise( (resolve, reject) => {
// Instantiates the XMLHttpRequest
var client = new XMLHttpRequest();
var uri = url;
if (args) {
uri += '?';
var argcount = 0;
for (var key in args) {
if (args.hasOwnProperty(key)) {
if (argcount++) {
uri += '&';
}
uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
}
}
}
client.open(method, uri);
client.send();
client.onload = function () {
if (this.status >= 200 && this.status < 300) {
// Performs the function "resolve" when this.status is equal to 2xx
resolve(this.response);
} else {
// Performs the function "reject" when this.status is different than 2xx
reject(this.statusText);
}
};
client.onerror = function () {
reject(this.statusText);
};
});
// Return the promise
return promise;
}
get(args) {
return this.ajax('GET', args);
}
post(args) {
return this.ajax('POST', args);
}
put(args) {
return this.ajax('PUT', args);
}
delete(args) {
return this.ajax('DELETE', args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment