MasterController
Action Filters
Authentication, logging, and shared setup — scoped to the actions that need it.
Filters run code around individual actions. Register them in the constructor with beforeAction / afterAction, passing the action names they apply to.
Before / after actions#
postsController.js
export default class PostsController {
constructor(requestObject) {
this.requestObject = requestObject;
// Guard mutating actions
this.beforeAction(['create', 'update', 'destroy'], (obj) => {
if (!obj.state.user) return this.returnError(401, 'Unauthorized');
this.next(); // continue to the action
});
// Audit after writes
this.afterAction(['create', 'update', 'destroy'], () => {
console.log('mutation performed');
});
}
async create(obj) { /* beforeAction ran first */ }
async update(obj) { /* ... */ }
}The contract#
beforeAction(actions, fn)— runsfn(obj)before each listed action. Callthis.next()to proceed, or send a response to short-circuit.afterAction(actions, fn)— runs after the action completes.this.next()— hands control from abeforeActionto the action.
Filters vs middleware
Use filters for controller-specific concerns (this controller’s auth rules). Use middleware for app-wide concerns (logging, body limits, CORS) that apply across every route.