Build a blog with Areto Node.js framework

Base controller

It is convenient to have a common controller methods collected in a single class. This purpose is served by the module/admin/component/Controller.js base controller in the admin module. The rest of the module controllers inherit from it directly or indirectly. The components module (application) directory contains the classes used in the models, controllers and views.

module/admin/component/Controller.js

const Base = require('areto/base/Controller');
module.exports = class Controller extends Base {
  // place methods here
};

The getModel method finds the object by the ID passed in GET parameter. The getModelClass method returns the model class. The found model will be loaded together with the relations, listed in the relations array. If a model is not found, the method will throw a 404 error.

module/admin/component/BaseController.js

getModel (params, cb) {
  params = params = Object.assign({
    'ModelClass': this.getModelClass(),
    'id': this.getQueryParam('id')
  }, params);
  if (!MongoHelper.isValidId(params.id)) {
    return this.throwNotFound();
  }
  let query = params.ModelClass.findById(params.id).with(params.with);
  async.waterfall([
    cb => query.one(cb),
    model => model ? cb(model) : this.throwNotFound()
  ], err => this.throwError(err));
}

The getRefUrl method returns the address of the previous page. Address is retrieved from the request header or POST parameter.

module/admin/component/BaseController.js

getRefUrl () {
  let ref = this.isGet()
    ? this.getHeader('referrer')
    : this.getBodyParam('referrer');
  return ref ? ref : '';
}

The backToRef method forwards the current request to the address obtained from the url argument or POST data.

module/admin/component/BaseController.js

backToRef (url = 'index') {
  let ref = this.getBodyParam('referrer');
  this.redirect(ref || url);
}