An isomorphic library for setting up Backbone models from a HAL API. Uses Traverson underneath.
var api = require('halbone')("http://api.com");
var Comments = Backbone.Collection.extend({
// ...
});
api.intercept(function(req) {
req.withRequestOptions({ headers: 'X-ACCESS-TOKEN': 'foo-token' });
});
api.get(Comments, 'posts[0].comments', function(err, comments) {
comments.fetch //...
comments.save //...
});
A working example using Artsy's API can be found here.
You may optionally pass an options object as the third arugment...
api.get(Post, 'posts[0]',{
bootstrap: POST_DATA,
qs: { querystring: true },
headers: { token: 'auth-me' },
params: { 'some-hal': 'template-params' }
}, function(err, post) {
//...
});
Aliases for Traverson's qs & headers options.
Alias for Traverson's URI Templates.
It's a common practice to bootstrap data you fetched on the server to the client to avoid making extra requests. By passing the bootstrapped data into the bootstrap
option, halbone will immediately return the hydrated model without making extra requests if it finds _links.self.href
, otherwise be sure to pass in the "root" link of the resource, e.g. 'posts', and it'll create a new model with the url injected (so model.save
can POST to right place). e.g.
POST_DATA = {}; // A new resource so empty data
api.get(Post, 'posts', { bootstrap: POST_DATA }, functionn(err, post) {
// post is a single resource with a url drawn from the 'posts' link.
// Allowing you to POST to it with a normal post.save
});
Please fork the project and submit a pull request with tests. Install node modules npm install
and run tests with npm test
.
MIT