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 module controllers inherit from it directly or indirectly.

The components module (application) directory contains classes used in 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 a object by ID passed in GET parameter. The getModelClass method returns a model class. The found model will be loaded together with relations, listed in the relations array. If a model is not found, the method will throw a 404 error.

module/admin/component/BaseController.js

async getModel (params) {
  params = {
    ModelClass: this.getModelClass(),
    id: this.getQueryParam('id'),
    ...params
  };
  if (!MongoHelper.isValidId(params.id)) {
    throw new BadRequest;
  }
  let model = new params.ModelClass({module: this.module});
  model = await model.findById(params.id).with(params.with).one();
  if (!model) {
    throw new NotFound;
  }
  return model;
}

createDataProvider (config) {
  return new ActiveDataProvider({
    controller: this,
    ...config
  });
}

async renderDataProvider (provider, template, data) {
  await provider.prepare();
  await this.render(template, data);
}

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

module/admin/component/BaseController.js

getReferrer () {
  const url = this.isGet()
    ? this.getHeader('referrer')
    : this.getPostParam('referrer');
  return url ? url : '';
}

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

module/admin/component/BaseController.js

redirectToReferrer (url = 'index') {
  this.redirect(this.getPostParam('referrer') || url);
}