modella-resource

Expose Modella models via RESTful resource middleware.

modella-resource

Expose Modella models via Express middleware. Adds REST routes with callbacks including self-describing OPTIONS response for each route.

This module can be paired with modella-ajax for automatic client-server communication.

npm install modella-resource

Pass a Modella model constructor to the modella-resource middleware and mount it:

var app = express();
  , modella = require('modella');
  , resource = require('modella-resource');
 
var User = modella('User');
 
app.use(resource(User).middleware());

These routes will then be available:

/users
    GET, POST, OPTIONS
/users/count
    GET, OPTIONS
/users/:id
    GET, PUT, DELETE, OPTIONS

If an OPTIONS request is made to any endpoint defined by modella-resource, a JSON description of the available actions is included in the response body.

You can combine this with OPTIONS middleware mounted at your API root path, which responds with a JSON description of the available resources.

You can override the resource actions if you want to customize the route callbacks. Each actions is called with arguments Model, req, res, next:

app.use(resource(User, {
  index:   function(Modelreqresnext) { },
  count:   function(Modelreqresnext) { },
  show:    function(Modelreqresnext) { },
  create:  function(Modelreqresnext) { },
  update:  function(Modelreqresnext) { },
  destroyfunction(Modelreqresnext) { }
});

You can nest resources using resource.add():

var UserResource = resource(User);
var PostResource = resource(Post);
 
app.use(UserResource.add(PostResource).middleware());

This creates routes such as /users/:id/posts and so on.

Returns Express/Connect middleware.