Article model

This class inherited from the Article of blog's frontend.

Article model

The safe rule applied to a files attribute does not perform any checks. It only means that a value of form data can be assigned to the attribute.


const Base = require('../../../model/Article');

module.exports = class Article extends Base {

  static getConstants () {
    return {
      ATTRS: [
      RULES: [
        [['title', 'content', 'status', 'date'], 'required'],
        ['title', 'string', {min: 3, max: 128}],
        ['title', 'unique'],
        ['content', 'string', {min: 10, max: 16128}],
        ['date', 'date'],
        ['category', 'id'],
        ['status', 'range', {range: [
        ['status', 'default', {value: this.STATUS_DRAFT}],
        ['files', 'safe'],
        ['tags', 'validateTags', {skipOnAnyError: true}]
      BEHAVIORS: {
        'timestamp': require('areto/behavior/TimestampBehavior')
        'status': {
          [this.STATUS_DRAFT]: 'Draft',
          [this.STATUS_PUBLISHED]: 'Published',
          [this.STATUS_ARCHIVED]: 'Archived',
          [this.STATUS_BLOCKED]: 'Blocked'
  // place methods here

const ArrayHelper = require('areto/helper/ArrayHelper');
const Comment = require('./Comment');
const Tag = require('./Tag');
const File = require('./File');
const Photo = require('./Photo');
const User = require('./User');

The findBySearch method searches for articles that contain a specified text in title.


findBySearch (text) {
  const query = this.find();
  if (typeof text === 'string' && /[a-z0-9\-\s]{1,32}/i.test(text)) {
    query.and(['LIKE','title', `%${text}%`]);
  return query;

The findToSelect method returns a query to select all titles of articles. The asRaw modifier sets the result as simple JavaScript objects.


findToSelect () {
  return this.find().select(['title']).asRaw();

By default, a new article gets the "draft" status.


constructor (config) {
  this.set('status', this.STATUS_DRAFT);

Photo processing

The beforeValidate handler is called before validation of a model. You must call the asynchronous parent method first to event system to work properly.


async beforeValidate () {
  await super.beforeValidate();
  await this.resolveFiles(this.get('files'));

The afterSave handler is called after a successful saving. The insert argument contains a flag that defines create or update a model by current action.


async afterSave (insert) {
  await super.afterSave(insert);
  await this.createPhotos(this.get('files'));

Asynchronous method resolveFiles finds models of uploaded files. Identifiers are received in a files serialized array of form.


async resolveFiles (files) {
  if (files && typeof files === 'string') {
    this.set('files', await File.findById(files.split(',')).all());
    await PromiseHelper.setImmediate();

The createPhotos method creates Photo models for uploaded files and links them to the current article. If you do not set a main article photo (mainPhotoId), the first of created models will be assigned as the main.


createPhotos (files) {
  if (!(files instanceof Array)) {
    return false;
  const photos = [];
  for (const file of files) {
    const photo = await this.createPhoto(file);
    if (photo) {
    await PromiseHelper.setImmediate();
  if (photos.length && this.get('mainPhotoId')) {
    // set first photo as main
    this.set('mainPhotoId', photos[0].getId());
    this.set('files', null);
    await this.forceSave();

async createPhoto (file) {
  const photo = this.spawn(Photo);
  photo.set('articleId', this.getId());
  photo.set('file', file);
  try {
    if (await {
      return photo;
  } catch (err) {
    this.log('error', err);

Tag processing

A serialized list of tag ids that are associated with an article is sent form. Method validateTags filters the empty and non-unique values, breaks off the current relations and creates new ones from received list.


async validateTags (attr, params) {
  let items = this.get(attr);
  if (typeof items !== 'string') {
  items = items.split(',').map(item => item.trim()).filter(item => item);
  items = ArrayHelper.unique(items);
  await this.unlinkAll('tags');
  for (const item of items) {
    await this.resolveTag(item);

The resolveTag method finds or creates a new tag model by name and links it to the current article.


resolveTag (name) {
  let model = await this.spawn(Tag).findByName(name).one();
  if (model) {
    return'tags', model);
  model = this.spawn(Tag);
  model.set('name', name);
  if (await {
    await'tags', model);

Article relations

The relAuthor relation defines article's author.

The relPhotos relation defines article's photos.

The relMainPhoto relation defines the main photos of article.

The relComments relation defines article's comments. The last argument in the hasMany function responsible for deleting comment's model at break of relations with article.

The relTags relation defines tags related to an article. The rel_article_tag junction table is used to link.


relAuthor () {
  return this.hasOne(User, User.PK, 'authorId');

relPhotos () {
  return this.hasMany(Photo, 'articleId', this.PK);

relMainPhoto () {
  return this.hasOne(Photo, Photo.PK, 'mainPhotoId');

relComments () {
  return this.hasMany(Comment, 'articleId', this.PK);

relTags () {
  return this.hasMany(Tag, Tag.PK, 'tagId').viaTable('rel_article_tag', 'articleId', this.PK);