Last active
August 29, 2015 13:56
-
-
Save vitalk/8971556 to your computer and use it in GitHub Desktop.
Example of the client-side API wrapper
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
// Define variables in one `var` statement | |
var | |
// The our API implementation | |
api = {}, | |
// The basic API endpoint | |
apiRoot = document.location.protocol + '//' + document.location.host + '/api/v1/', | |
// Verb aliases | |
GET = 'GET', | |
POST = 'POST', | |
DELETE = 'DELETE'; | |
function normalizeUrl(url) { | |
return apiRoot + url; | |
}; | |
function request(verb, url, callback) { | |
var xhr = createXMLHttpRequest(); | |
callback = callback || function() {}; | |
// XXX: normalize API url in one location – not per api method | |
xhr.open(verb, normalizeUrl(url), true); | |
xhr.setRequestHeader('Accept', 'application/json'); | |
xhr.onload = function () { | |
callback(JSON.parse(this.responseText), this) | |
}; | |
xhr.send(); | |
}; | |
function createXMLHttpRequest() { | |
return (window.XMLHttpRequest) | |
? new XMLHttpRequest() | |
: new ActiveXObject("Microsoft.XMLHTTP"); | |
}; | |
api.query = function(id) { | |
if (!(this instanceof api.query)) { | |
return new api.query(id); | |
} | |
this.id = id; | |
}; | |
api.query.all = function(callback) { | |
request(GET, 'queries', callback); | |
return this; | |
} | |
api.query.prototype.remove = function(callback) { | |
request(DELETE, 'queries/' + this.id, callback); | |
return this; | |
}; | |
api.query.prototype.mute = function(callback) { | |
request(POST, 'queries/' + this.id + '/mute', callback); | |
return this; | |
}; | |
api.query.prototype.unmute = function(callback) { | |
request(POST, 'queries/' + this.id + '/unmute', callback); | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment