Skip to content

Instantly share code, notes, and snippets.

@raysuelzer
Last active August 29, 2015 14:17
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 raysuelzer/45138a14a29208b22e2d to your computer and use it in GitHub Desktop.
Save raysuelzer/45138a14a29208b22e2d to your computer and use it in GitHub Desktop.
chainable api?
//Fetch data from the API using dot notation.
//Only used when the dot notation will result in a valid URI
ApiClient.fetchData("parent_employers.2.work_sites")
.done((data) => {
console.log(data);
});
//More advanced chaining
//Fetch data from the api using chained functions
ApiClient.parent_employers({id: 2}) //params replace templated uris
.work_sites({id: 1})
.departments({page: 1})
.fetch() //returns a promise
.then(doSomething);
const api_client = {
var builturi = "api/v1";
parent_employers(params) {
//do some magic to add the templated uri to the build uri
builturi += uri_components.parent_employers.expand_uri(params);
return this;
//returns back api_client instance
},
work_sites(params) {
builturi += uri_components.work_sites.expand_uri(params);
return this;
//returns back api_client instance
},
fetch() {
return request(builturi); //return ajax request of built uri
}
}
const uri_components = {
parent_employers: {
templates: {
get_by_id: "/parent_employers/{id}",
list: "/parent_employers{?page}{?blah}"
},
},
work_sites: {
templates: {
get_by_id: "/work_sites/{id}",
list: "/work_sites{?page}{?params}"
}
}
//....
}
function make_uri(rel, params) {
if (params.id typeof number)
return uri_components[rel].templates.get_by_id
.replace({id}, params.id);
else
return //code to replace the other templates
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment