foraker
Foraker provides a simple, drop-in controller that support filters, promises, subclassing, and more. It's easy to integrate into existing Express / middleware based apps, follows the "do one thing well" principle, and is thoroughly tested.
Note: this is alpha software, and still undergoing changes. Contributions welcome, consumers beware 😉
Install
$ npm install --save foraker
Basic Usage
// controllers/posts.js; ;
Express / Connect Integration
Controllers are stand alone code - you need to wire them up to your Express (or otherwise Connect-compatible) routing layer to let them actually handle requests:
// app.js; // Controller singletonlet posts = ; app;
Filters
Filters operate much like Rails filters: they allow you to run code before or after an action handler runs.
Filters can be applied to specific actions, are inherited from superclasses, and can be skipped. They receive the req and res just like a regular action handler, and if they throw an error or send a response, the request handling stops there (i.e. later filters or actions are not run).
Here's a basic example of a controller with a single action (update
), and a single before filter that applies to all actions on the controller which will authenticate the user:
// controllers/posts.js; ;
In this more complex example, the filters are applied selectively using the only
and except
options:
{ // The `only` option acts like a whitelist, so the notifyAuthor filter is // only run for the update action. `except` acts like a blacklist, // preventing the filter from running on specific actions. this; }
You can also pass the filter method directly in, rather than referencing it by name. This is useful if the filter method isn't a method defined on the controller class itself:
;;
Subclassing
Foraker Controllers use core-object to provide inheritance functionality. You can extend the base Controller class via Controller.extend
, which will then be available on your subclass as well:
; let BaseController = Controller;let SubclassedController = BaseController;
core-object also provides convenient super functionality:
; let NameController = Controller; let PoliteNameController = NameController;
Controllers with filters are intelligent about how they handle subclasses. Child classes will run the parent class filters as well:
; let ApplicationController = Controller; let BooksController = ApplicationController;
Parent class before filters will run prior to the child class before filters, and parent class after filters will run following the child class after filters.
License
MIT © Dave Wasmer