go-ike / ike

1 stars 1 forks source link

Controller super class #6

Open mateusnroll opened 7 years ago

mateusnroll commented 7 years ago

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

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