Build a blog with Areto Framework

Photo controller

The PhotoController class defines a controller of the photo model.


const Base = require('../component/CrudController');

module.exports = class PhotoController extends Base {

  static getConstants () {
    return {
      METHODS: {
        'assign-main': ['post']

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.


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

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


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.


async actionUpload () {
  let file = this.spawn(File);
  if (!await file.upload(this)) {
    return this.sendText(this.translate(file.getFirstError()), 400);
  let photo = this.spawn(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.


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]);