Skip to content

njkleiner/controller-base

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

controller-base

A (CRUD) controller template for MVC in Express.

Getting Started

Installing

$ npm install controller-base

Usage

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);

Contributing

This project uses the git branching model described here.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License. See the LICENSE.md file for details.

Acknowledgments

About

A (CRUD) controller template for MVC in Express.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published