Skip to content

Instantly share code, notes, and snippets.

@mendelgusmao
Created June 14, 2012 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mendelgusmao/2931935 to your computer and use it in GitHub Desktop.
Save mendelgusmao/2931935 to your computer and use it in GitHub Desktop.
AJAX Fluent Interface
function AJAXFluentInterface(uri) {
this.uri = uri || "";
this.retrieve = function(data, type) {
return $.ajax({
type: type || "GET",
url: this.uri,
dataType: "json",
data: data
})
};
this.registerEndpoint = function(endpoint, methods) {
if (endpoint == "") {
return;
}
var splittedEndpoint = endpoint.split("/");
methods = methods || ["GET"];
if (splittedEndpoint[0] == "") {
splittedEndpoint.splice(0, 1);
}
var part = splittedEndpoint[0];
if (this[part] === undefined) {
this[part] = new AJAXFluentInterface([this.uri, part].join("/"));
}
for (i in methods) {
this[part][methods[i].toLowerCase()] = function(data) {
return this.retrieve(data, methods[i]);
}
}
splittedEndpoint.splice(0, 1);
this[part].registerEndpoint(splittedEndpoint.join("/"), methods);
};
this.compile = function() {
/* TODO
Concept:
registerEndpoint("/foo/bar")
-> .foo.bar == .foo.bar.get
*/
}
}
application = new AJAXFluentInterface();
application.registerEndpoint("/auth/Login", ["POST"]);
application.registerEndpoint("/auth/Logout");
application.registerEndpoint("/auth/foo/bar/baz/xpto/ximbica");
console.log(application);
console.log(application.auth.uri);
console.log(application.auth.Login.uri);
console.log(application.auth.Logout.uri);
console.log(application.auth.foo.bar.baz.xpto.ximbica.uri);
application.auth.Login.post({username: "admin", password: "admin"}).done(function(e) {
console.log(e);
});
application.auth.Logout.get().done(function(e) {
console.log(e);
});
application.auth.get().done(function(e) {
console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment