Skip to content

Instantly share code, notes, and snippets.

@pfrazee
Created November 30, 2012 05:35
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 pfrazee/4173942 to your computer and use it in GitHub Desktop.
Save pfrazee/4173942 to your computer and use it in GitHub Desktop.
hateoas
// HATEOAS
// if it's going to be the engine of application state........
// simple example
// ==============
var localStorage = link('httpl://localstorage.api');
var settings = localStorage.collection('settings');
settings.record('user').get(function(user) {
//...
});
// simple example's hidden protocol
// ================================
var localStorage = link('httpl://localstorage.api');
// since we havent retrieved localstorage's links yet, this next call will queue the link-follow to the collection
// (that is, `settings` becomes a plan to follow the settings collection link, if possible)
var settings = localStorage.collection('settings');
// now we add another link follow (user record), and then we actually execute the link-follow plan with a GET
settings.record('user').get(function(user) {
//...
});
// this results in 3 requests:
HEAD 'httpl://localstorage.api'
-> [ { href:'httpl://localstorage.api/settings', rel:'collection', title:'settings' } ]
HEAD 'httpl://localstorage.api/settings'
-> [ { href:'httpl://localstorage.api/settings/{record}', rel:'record' } ]
GET 'httpl://localstorage.api/settings/user'
// if any of those had failed, get()'s error callback (not specified in the example) would have been invoked
// `settings` and `localStorage` now have the links cached, so the same call...
settings.record('user').get(/*...*/)
// only results in GET httpl://localstorage.api/settings/user
// another example
// ===============
var github = link('https://api.github.com');
var me = github.collection('users').record('pfrazee');
me.get(function(profile) {
profile.email = 'pfrazee@gmail.com';
this.put(profile);
});
// parameter 2 is extra uri template data
// presumably, this link's href looks like "https://api.github.com/users/pfrazee/{collection}/{?age}"
me.collection('friends', { age:'> 20' }).get(function(friends) {
friends.forEach(function(friend) {
this.record(friend.id).patch({ some:'value' });
}, this);
});
// collections with pagination could basically be batch iterators:
batchIterator(
me.collection('friends', { age:'> 20' }).get(),
function(friends) { return friends.next(); },
function(friend) {
this.record(friend.id).patch({ some:'value' });
}
});
http://www.iana.org/assignments/link-relations/link-relations.xml
http://visionmedia.github.com/superagent/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment