User model

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

View user model

User password is required to create a model and is optional for editing. It provides validation scenarios assigned to rules 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 a value belonging to a set.

module/admin/model/User.js

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

module.exports = class User extends Base {

  static getConstants () {
    return {
      RULES: [
        [['name', 'email', 'role', 'status'], 'required'],
        ['password', 'required', {on: ['create']}],
        ['status', 'range', {range: [
          this.STATUS_PENDING,
          this.STATUS_ACTIVE,
          this.STATUS_BANNED
        ]}],
        ['role', 'range', {range: [
          this.ROLE_READER,
          this.ROLE_AUTHOR,
          this.ROLE_EDITOR,
          this.ROLE_MODERATOR,
          this.ROLE_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}]
      ],
      ATTR_VALUE_LABELS: {
        'status': {
          [this.STATUS_ACTIVE]: 'Active',
          [this.STATUS_BANNED]: 'Banned'
        },
        'role': {
          [this.ROLE_READER]: 'Reader',
          [this.ROLE_AUTHOR]: 'Author',
          [this.ROLE_EDITOR]: 'Editor',
          [this.ROLE_MODERATOR]: 'Moderator',
          [this.ROLE_ADMIN]: 'Administrator'
        }
      }
    };
  }
  // place methods here
};
module.exports.init(module);

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

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

module/admin/model/User.js

findBySearch (text) {
  if (!text) {
    return this.find();
  }
  return this.find(['OR',
    ['LIKE','name',`%${text}%`],
    ['LIKE','email',`%${text}%`]
  ]);
}

The relArticles relation finds all articles per user.

module/admin/model/User.js

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