Skip to content

Controller super class #6

@mateusnroll

Description

@mateusnroll

Just like Rails, where ike drinks from a lot, every controller should have a super class which enforces some default behaviours and creates helpful lifecycle hooks.

Basic definitions

  • The name should be IkeRouter, because of reasons. 👍
  • Every controller should be a subclass of it.
  • Controller naming convention should be a recommendation, not enforcement.

Features

Before and after action hooks
Controllers should handle its businesses, and before and after hooks makes it possible to take care of such things. It is a good idea to use express' middleware functions, since this will be available to the router when instantiating the class. Using authentication and permissions as a simple example, it could look like this:

class SamplesController extends IkeController {
    constructor() {
        this.beforeEach = [this._verifyLogin()];
        ...
    }
    ...
    
    /*private*/

    _verifyLogin() {
        if(someCondition) next();
        else res.redirect('/unauthorized');
    }
}

Avoid receiving req and res on every method
It is possible to attach it to the class scope while creating the class instance for the route, and avoid duplicating it everywhere.

class SamplesController extends IkeController {
    constructor() {...}
    index() { // No req or res on the method, it's attached to the instance
        let params = req.params;
        res.send(params);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions