Refactoring the Code Using Promise/Async/Await

// controllers/dashboard/author.js
class Author{
  constructor(){
    this.deepcopy = require('deepcopy');
    this.vdict = require('../../config');
    this.utility = require('../../utility');
    this.usersdb = require('../../models/usersdb');
    this.emailCheck = require('email-check');
    this.bcrypt = require('bcryptjs');
  }

  async getAuthor(req, res){
    const self = this;
    const data = this.deepcopy(this.vdict);
    data.site_title = 'ទំព័រ​អ្នក​និពន្ធ';
    data.date = this.utility.setDate();
    data.authors = await this.usersdb.selectUser(this.vdict.dashboardLimit); 
    data.thumbs = self.utility.getThumbUrl(data.authors, 'author');
    data.count = await self.usersdb.countUser();
          
    if(req.params.authorId){
      data.edited = await self.usersdb.selectUser(self.vdict.dashboardLimit, req.params.authorId);
      res.render('dashboard/author', data);
    }else
      res.render('dashboard/author', data);
  }

  async postAuthor(req, res){
    const self = this;
    const data = this.deepcopy(this.vdict);
    data.site_title = 'ទំព័រ​អ្នក​និពន្ធ';
    data.date = this.utility.setDate();
  
    if(req.session.user.role == 'Admin'){
      const user = await this.usersdb.checkEmail(req);
      if(user){
        data.authors = await self.usersdb.selectUser(self.vdict.dashboardLimit);
        data.thumbs = self.utility.getThumbUrl(data.authors, 'author');
        data.count = await self.usersdb.countUser();
        data.message = 'Email នេះ​មាន​គេ​ប្រើ​ប្រាស់​ហើយ​';
        res.render('dashboard/author', data);
      }else{
        self.emailCheck(req.body.email)
          .then(async function (result) {
            if(result){
              const user = await self.usersdb.insertUser(req);
              data.authors = await self.usersdb.selectUser(self.vdict.dashboardLimit); 
              data.thumbs = self.utility.getThumbUrl(data.authors, 'author');
              data.count = await self.usersdb.countUser();
              data.message = `អ្នក​និពន្ធ​ ${user.username} ត្រូវ​បានចុះ​បញ្ជី​រួច​ហើយ`;
              res.render('dashboard/author', data);  
            }
          }).catch(async function (err) {
            data.authors = await self.usersdb.selectUser(self.vdict.dashboardLimit);
            data.thumbs = self.utility.getThumbUrl(data.authors, 'author');
            data.count = await self.usersdb.countUser();
            data.message = 'Email នេះ​មិន​ត្រឹមត្រូវ​ទេ';
            res.render('dashboard/author', data);
          });
      }

    }else{
      data.authors = await this.usersdb.selectUser(self.vdict.dashboardLimit);
      data.thumbs = self.utility.getThumbUrl(data.authors, 'author');
      data.count = await self.usersdb.countUser();
      data.message = 'មាន​តែ Administrator ទេ ​ដែល​អាច​ចុះ​បញ្ជី​អ្នក​និពន្ធ​បាន​';
      res.render('dashboard/author', data);
    }
  }

  async updateAuthor(req, res){
    const self = this;
    const data = this.deepcopy(this.vdict);
    data.site_title = 'ទំព័រ​អ្នក​និពន្ធ';
    data.date = this.utility.setDate();
    
    if((req.session.user.role === "Admin") || (req.session.user.userid === req.params.authorId)){
      const user = await this.usersdb.checkEmail(req);
      
      if(user && (req.params.authorId != user.userid)){
        data.authors = await self.usersdb.selectUser(self.vdict.dashboardLimit);
        data.thumbs = self.utility.getThumbUrl(data.authors, 'author');
        data.count = await self.usersdb.countUser();
        data.message = 'Email នេះ​មាន​គេ​ប្រើ​ប្រាស់​ហើយ​';
        res.render('dashboard/author', data);
      }else{
        self.emailCheck(req.body.email)
          .then(async function (result) {
            if(result){
              if((req.session.user.role === "Admin") || (req.session.user.userid === user.userid)){
                data.author = await self.usersdb.updateUser(req);
                data.message = `ទិន្នន័យ​អ្នក​និពន្ធ​ ${data.author.username} ត្រូវ​បាន​កែ​តំរូវ​`;
                data.authors = await self.usersdb.selectUser(self.vdict.dashboardLimit);
                data.thumbs = self.utility.getThumbUrl(data.authors, 'author');
                data.count = await self.usersdb.countUser();   
                res.render('dashboard/author', data);
              }
            }
          })
          .catch(async function (err) {
            data.authors = await self.usersdb.selectUser(self.vdict.dashboardLimit);
            data.thumbs = self.utility.getThumbUrl(data.authors, 'author');
            data.count = await self.usersdb.countUser();
            data.message = 'Email នេះ​មិន​ត្រឹមត្រូវ​ទេ';
            res.render('dashboard/author', data);
          });
      }
    
   }else{
      data.authors = await this.usersdb.selectUser(self.vdict.dashboardLimit);
      data.thumbs = self.utility.getThumbUrl(data.authors, 'author');
      data.count = await self.usersdb.countUser();
      data.message = 'មាន​តែ Administrator ឬ​សមី​ខ្លូន​ទេ ដែល​អាច​ដូរ​ទិន្នន័យអ្នក​​និពន្ធ​បាន​';
      res.render('dashboard/author', data);
    }
  }

}//end class

module.exports = new Author();
// models/usersdb.js
class Usersdb{
  constructor(){
    const mongoose = require('mongoose');
    const bcrypt = require('bcryptjs');

    const usersSchema = new mongoose.Schema({
      username: {type: String, required: true},
      userid: {type: String, required: true},
      password: {type: String, required: true},
      email: {type: String, required: true},
      role: {type: String, required: true},
      info: {type: String, required: false},
      date: {type: Date, required: true}
    });

    const users = mongoose.model('users', usersSchema);
    this.users = users;
    this.bcrypt = bcrypt;

    users.findOne(function (err, user){
      if (err) return console.error(err);
      if(!user){
        const hash = bcrypt.hashSync('password', 12);
        const id = (new Date()).getTime().toString(36) + Math.random().toString(36).slice(2);
        const root = new users({userid:id, username:'root', password:hash, email:'root@multimedia.com', role:'Admin', info:'test', date: new Date()});
        root.save(function (err, root){
          if (err) return console.error(err);
        });
      }
    });
  }

  checkUser(req, callback){
    this.users.findOne({email:req.body.email}, function (err, user){
      if (err) return console.error(err);
      return callback(user);
    });
  }

  async checkEmail(req){
    return await this.users.findOne({email:req.body.email});
  }

  async insertUser(req){
    const hash = this.bcrypt.hashSync(req.body.password, 12);
    const id = (new Date()).getTime().toString(36) + Math.random().toString(36).slice(2);
    const user = new (this.users)({userid:id, username:req.body.username, password:hash, email:req.body.email, role:req.body.role, info:req.body.info, date: new Date(req.body.date)});
    return await user.save();
  }

  async selectUser(amount=5, id=false){
    if(id){
      return await this.users.findOne({userid: id});
    }else{
      return await this.users.find().sort({date: -1, _id: -1}).limit(amount);
    }
  }

  async countUser(){
    return await this.users.countDocuments({});
  }

  async updateUser(req){
    const user = await this.users.findOne({userid:req.params.authorId});
    user.username = req.body.username;
    user.email = req.body.email;
    user.role = req.body.role;
    user.info = req.body.info;
    user.date = new Date(req.body.date);
    return await user.save();
  }

}//end class

module.exports = new Usersdb();

GitHub: "https://github.com/Sokhavuth/multimedia
Heroku: https://khmerweb-multimedia.herokuapp.com/

Comments

Popular posts from this blog