Build a blog with Areto Node.js framework

User model

In the admin module uou can update a user created by the registration form and to create new ones. The user class inherits from the User of the frontend of the blog.

View user model

User password is required to create the model and is optional for editing. It provides validation scenarios assigned to the rule when creating ({on: ['create']}). Thus, the password attribute is mandatory only with ['create'].includes(model.scenario) condition. If a scenario for a rule is not specified, the rule will be applied in all cases.

The range validator used for the status, role attributes to check the value belonging to the set.

modules/admin/models/User.js

'use strict';
const Base = require('../../../models/User');
module.exports = class User extends Base {
  static getConstants () {
    return {
      RULES: [
        [['name', 'email', 'role', 'status'], 'required'],
        ['password', 'required', {on: ['create']}],
        ['status', 'range', {range: ['pending', 'active', 'banned']}],
        ['role', 'range', {range: ['reader', 'author', 'editor', 'moderator', 'admin']}],
        ['name', 'string', {min: 3, max: 24}],
        ['name', 'regexp', {pattern: /^[a-z\s-]+$/i}],
        ['email', 'email'],
        ['password', 'string', {min: 6, max: 32}],
        [['email', 'name'], 'unique', { ignoreCase: true }]
      ]
    };
  }
  // place methods here
};
module.exports.init(module);
const Article = require('./Article');

The findBySearch method searches for users whose name or email containing the given text.

modules/admin/models/User.js

...
static findBySearch (text) {
  let query = this.find();
  if (text) {
    query.andWhere(['OR', ['LIKE','name',`%${text}%`], ['LIKE','email',`%${text}%`]]);
  }
  return query;
}
...

Methods return a list of valid values and names of the status, role attributes.

modules/admin/models/User.js

...
getStatusSelect () {
  return [
    { value: 'active', label: 'Active' },
    { value: 'banned', label: 'Banned' }
  ];
}

getRoleSelect () {
  return [
    { value: 'reader', label: 'Reader' },
    { value: 'author', label: 'Author' },
    { value: 'editor', label: 'Editor' },
    { value: 'moderator', label: 'Moderator' },
    { value: 'admin', label: 'Administrator' }
  ];
}
...

The relArticles relation finds all articles per user.

modules/admin/models/User.js

...
relArticles () {
  return this.hasMany(Article, ['authorId', this.PK]);
}
...