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 modules/admin/components/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.

modules/admin/components/Controller.js

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

The isValidId static method validates the object identifier.

modules/admin/components/Controller.js

...
static isValidId (id) {
  return id && /^[a-f0-9]{24}$/.test(id);
}
...

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.

modules/admin/components/Controller.js

...
getModel (cb, ...relations) {
  let id = this.getQueryParam('id');
  if (this.constructor.isValidId(id)) {
    this.getModelClass().findById(id).with(relations).one((err, model)=> {
      err ? this.throwError(err)
          : model ? cb(model) : this.throwNotFound();
    });
  } else this.throwNotFound();
}
...

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

modules/admin/components/Controller.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.

modules/admin/components/Controller.js

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