A (CRUD) controller template for MVC in Express.
$ npm install controller-base
The controller follows the Ruby on Rails methodology.
All action methods are asynchronous so that you can easily use the async
/await
syntax when implementing them. They are wrapped using a higher-order function that passes errors to the next handler in the chain.
Each method has the following signature: async $action(request, response, next)
, the controller will register the following action methods by default:
$index
$new
$create
$show
$edit
$update
$destroy
Simply extend the controller class and override the $action
methods and add your own actions as needed.
// controllers/account.js
const Controller = require('controller-base');
class AccountsController extends Controller {
async $index(request, response, next) {
// List all accounts...
}
// Implement the other $action methods as needed.
// Add a custom $action
// NOTE: Unlike the default methods, this one is not declared using the `async` keyword.
$action(request, response, next) {
response.send('/action');
}
// Override the configure method to register your custom action.
configure(router) {
// Call the super method to configure the default actions.
super.configure(router);
// And configure your custom action.
const self = this;
router.get('/action', (request, response, next) => self.$action(request, response, next));
}
}
module.exports = new AccountsController();
Then call the configure
method on your controller instance and pass it a Router object.
const AccountsController = require('./controllers/account');
const router = new express.Router();
AccountsController.configure(router);
// ...
app.use('/accounts', router);
This project uses the git branching model described here.
We use SemVer for versioning. For the versions available, see the tags on this repository.
See also the list of contributors who participated in this project.
This project is licensed under the MIT License. See the LICENSE.md file for details.
- This project is inspired by Ruby on Rails.
- README template by Billie Thompson.