This is patterned off of Angular's $resource service, except that it does not depend on Angular and uses superagent instead of $http. Route parsing is done with the route-parser module.
var superRes = require('super-res');
var myResource = superRes.resource('/my-endpoint/:id')
myResource.get({id: 1})
.then(function (responseData) {
console.log(responseData);
});
myResource.save({id: 1}, {content: 'some sort of content'})
.then(function (responseData) {
console.log(responseData);
});
The options and interface defined in the $resource doc is accurate (aside from the missing features and differences mentioned later)
Caching is handled by the cache-manager node module. If you create an action with the cache option set to true, it will use cache-manager's default in-memory cache with a max size of 100 items and a max age of 20 minutes. Or, you can provide your own cache object, so long as it follows the cache-manager interface.
There is also a function called promiseWrapper, which will wrap the promises returned by each action with an instance of $q passed to it. This is helpful if you want to use it with Angular:
angular.module('test', []).factory('myResource', function ($q) {
var superRes = require('super-res');
return superRes.promiseWrapper($q.when)(superRes.resource('/my-endpoint/:id'));
});
//somewhere else
myResource.get({id: 1}; // returns a promise wrapped in $q.when() to hook into digest cycle
Here's what's on the list to add:
- batching
- Entirely promise based. No $promise or $resolved properties.
- The data returned is just an object, it does not have any resource functions attached.
- isArray doesn't do anything. I haven't seen a use case for it (arrays and objects work as you'd expect).
- Includes a default PUT action (called put).
- Transforms are passed a headers object as the second argument, rather than a getter.
- Superagent will automatically parse certain response types. This is not suppressed by passing a responseTransform of [].
- Excess default parameters are not automatically added to the query string if they're not in the route template (PRs welcome for this).
Additionally to the angular resource options, superagent plugins can be configured for each resource action.
var nocache = require('superagent-no-cache');
var prefix = require('superagent-prefix');
var myResource = superRes.resource('/my-endpoint/:id', {
action: {
method: 'GET',
plugins: [nocache, prefix('/static')]
}
})