Build a blog with Areto Node.js framework

Photo controller

The PhotoController class defines a controller of the photo model.

module/admin/controller/PhotoController.js

const Base = require('../component/CrudController');
module.exports = class PhotoController extends Base {

  static getConstants () {
    return {
      METHODS: {
        'assign-main': ['post']
      }
    };
  }
};
module.exports.init(module);
const Article = require('../model/Article');
const File = require('../model/File');
const Photo = require('../model/Photo');
Create photo

The actionCreate method creates a photo model. The async.series array of asynchronous methods receives data to select one article of the list (Article.findToSelect). You can assign a photo to it.

module/admin/controller/PhotoController.js

async actionCreate () {
  let model = new Photo;
  model.scenario = 'create';
  if (this.isPost() && model.load(this.getBodyParams()).save()) {
    return this.backToRef();
  }
  await this.render('create', {
    articles: await Article.findToSelect().all(),
    model
  });
}
View uploaded photo

The actionView method calls the parent to get the necessary relations.

module/admin/controller/PhotoController.js

async actionView () {
  await super.actionView({
    with: ['article']
  });
}
Update photo

The actionUpload method uploads a file to the server. If the file is validated, a photo model will be created. Initial model is not linked to any article.

module/admin/controller/PhotoController.js

async actionUpload () {
  let file = new File;
  if (!await file.upload(this)) {
    return this.sendText(this.translate(file.getFirstError()), 400);
  }
  let photo = new Photo;
  photo.set('file', file.getId());
  await photo.validate(['file'])
    ? this.sendText(file.getId())
    : this.sendText(this.translate(photo.getFirstError()), 400);
}

The actionAssignMain method sets the main photo of the article. The forceSave function saves article without any data validation. If the photo is not related to any article, then set flash error messages (one-off message to a user session), and user will be redirected to the viewing page.

module/admin/controller/PhotoController.js

async actionAssignMain () {
  let model = await this.getModel({
    with: ['article']
  });
  let article = model.get('article');
  if (!article) {
    this.setFlash('danger', 'Article not found');
    return this.redirect(['view', model]);
  }
  article.set('mainPhotoId', model.getId());
  await article.forceSave();
  this.redirect(['article/view', article]);
}