Build a blog with Areto Node.js framework

Comment model

The Comment class defines a model of the commentary to the article. Users can comment without authentication. But any comment will be published after moderation only.

List of comments to article

Each comment has a few conditions:

  • STATUS_PENDING - comment is awaiting moderation.
  • STATUS_APPROVED - approved comment.
  • STATUS_REJECTED - rejected comment.

The BEHAVIORS static property contains behaviors that will be assigned to an instance of the class. Behavior defines a set of event handlers of the target model and the associated functionality. In this case, the timestamp behavior sets the current time to the createdAt, updatedAt attributes when you create or edit a comment.

models/Comment.js

'use strict';
const Base = require('areto/db/ActiveRecord');
module.exports = class Comment extends Base {

  static getConstants () {
    return {
      TABLE: 'comment',
      STORED_ATTRS: ['articleId', 'name', 'email', 'ip', 'content', 'status', 'createdAt', 'updatedAt'],
      RULES: [
        [['name','email','content'], 'required'],
        ['name', 'string', {min: 2, max: 32}],
        ['email', 'email'],
        ['content', 'string', {min: 3, max: 512}]
      ],
      BEHAVIORS: {timestamp: require('areto/behaviors/Timestamp')},
      STATUS_PENDING: 'pending',
      STATUS_APPROVED: 'approved',
      STATUS_REJECTED: 'rejected'
    };
  }

  // place methods here
};
module.exports.init(module);
Comment form

Every new comment has the status of "Pending moderator" by default.

models/Comment.js

...
init () {
  super.init();
  this.set('status', this.STATUS_PENDING);
}
...

Set the contents of the comment as a model header.

models/Comment.js

...
getTitle () {
  return this.get('content');
}
...

The following methods are required to check the status of a comment.

models/Comment.js

...
isPending () {
  return this.get('status') === this.STATUS_PENDING;
}

isApproved () {
  return this.get('status') === this.STATUS_APPROVED;
}

isRejected () {
  return this.get('status') === this.STATUS_REJECTED;
}
...