Skip to content

Instantly share code, notes, and snippets.

@couchoud
Created August 19, 2010 13:20
Show Gist options
  • Save couchoud/537851 to your computer and use it in GitHub Desktop.
Save couchoud/537851 to your computer and use it in GitHub Desktop.
post_4 - cs2
/*!
* Javascript Pattern for Rest Service API’s
* http://www.chriscouchoud.com/
*
* Dual licensed under the MIT and GPL licenses.
*/
service = {
baseURL : "http://www.yourrestapi.com",
/**
Delegate for the jquery.ajax call that provides for some extended pre/post call functionality.
@param {String} descriptor type of service request to make
@param {Object} resource data object used to map the ajax call
@param {Object} [options] optional jquery ajax options object that can be used to define
custom parameters for the ajax request. This often will include
specific success and error handlers specific to the call you are
making and probably some data that you went sent along in the
request.
*/
create : function(descriptor, resource, options) {
// match up the service definition
var def = serviceDefinitions[descriptor];
/**
udpate the default options on the jQuery ajax object using
the values defined in the definition
*/
// here we map the resource to the url defined in the definition
options.url = this._mapResourceToUrl(def.url, resource);
options.type = def.type || "GET";
options.dataType = def.dataType || "json";
options.contentType = def.contentType || "application/x-www-form-urlencoded";
// make the ajax call
$.ajax(options);
},
/**
Matches {PROPERTY_NAME} in the url with the corressponding
property value in resource
property value can be a String, Number, or Function that returns
a string
@param {Object} resource object with properties to map
@param {String} url string with 'foo/{PROPERTY_NAME}/' format
*/
_mapResourceToUrl : function(resource, url) {
url = this.baseURL + url;
return url.replace(/{([^{}]*)}/g,
function (a, b) {
var r = resource[b],
value = r;
// special handling numbers and functions
if(typeof r === 'number') {
value = r + "";
}
else if(typeof r === 'function') {
// pass in resource as the scope
value = r.call(resource);
}
// ensure a string is returned
return (typeof value === 'string') ? value : a;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment