Skip to content

Instantly share code, notes, and snippets.

@stevenschobert
Created December 2, 2014 20:02
Show Gist options
  • Save stevenschobert/7ac462076f71d9270785 to your computer and use it in GitHub Desktop.
Save stevenschobert/7ac462076f71d9270785 to your computer and use it in GitHub Desktop.
Some bare-bones Request/Response prototypes for JavaScript. Wraps XMLHttpRequest.
/**
* Request class for making HTTP requests.
*
* new Request('http://api.com', {
* method: 'get',
* headers: {}
* }).send(function(res) {});
*/
function Request(url, opts) {
opts = opts || {};
this.url = url;
this.headers = opts.headers || {};
this.method = opts.method || 'get';
}
/**
* Sends the request object. Accepts and callback function
* that receives a Response object.
*/
Request.prototype.send = function sendRequest(callback) {
var request = new XMLHttpRequest();
var self = this;
/**
* Callback wrapper that creates a #Response object.
*/
request.onload = function handleResponse() {
var res = new Response(request);
callback.call(self, res);
};
/**
* Opens the XMLHttpRequest so headers can be set.
*/
request.open(this.method, this.url);
/**
* Sets requet headers from the @headers property.
*/
Object.keys(this.headers).forEach(function setHeader(header) {
request.setRequestHeader(header, this.headers[header]);
}, this);
/**
* Sends the request
*/
request.send();
return this;
};
/**
* Convenience method for sending a get request
* without having to create an instance.
*/
Request.get = function get(url, headers, callback) {
if (arguments.length < 3) {
callback = headers;
}
return new Request(url, {
method: 'get',
headers: headers || {}
}).send(callback);
};
/**
* Reponse class. Wraps an XMLHttpRequest instance.
*/
function Response(xmlreq) {
if (xmlreq) {
this.status = xmlreq.status;
this._parseHeaders(xmlreq.getAllResponseHeaders());
if (this.headers['Content-Type'] && /application\/json/.test(this.headers['Content-Type'])) {
this.body = JSON.parse(xmlreq.responseText);
} else {
this.body = xmlreq.responseText || '';
}
}
}
/**
* Parses a header string into a @headers property.
*/
Response.prototype._parseHeaders = function parseHeaders(headers) {
var splitHeaders = headers.split('\n');
var headerRegExp = /^(.*):(.*)$/;
var headersMap = {};
splitHeaders.forEach(function processHeader(header) {
var strippedHeader = header.replace(/\s/mg, '');
var headerParsed = headerRegExp.exec(strippedHeader);
if (headerParsed && headerParsed.length >= 3) {
headersMap[headerParsed[1]] = headerParsed[2];
}
});
this.headers = headersMap;
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment