Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

88
Views
How to send response from class object promise to controller in nodeJS

I have a question. I am using a NodeJS app divided in three main parts

  1. Data access object Here, I created a function that make the direct interaction with the database only in this file.

    const { response } = require('express'); const db = require('../connection/db.js');

    /* Export */ module.exports = { // Insert User insertUser: (parameters) => { const sqlStatement = 'INSERT INTO users SET ?'; return new Promise((resolve, reject) => { db.query(sqlStatement, parameters, (error, response) => { if (error) { return reject(error); } return resolve(response); }) }) } }

  2. Object class In this class I will make the validation, and create the method with arguments, then implement the data access object insertUser.

     const db = require('../dataAccessObject/dao.js');
    

    class User { constructor (fname, lname, age, email, password, avatar, gender) { this.fname = fname; this.lname = lname; this.age = age; this.email = email; this.password = password; this.avatar = avatar; this.gender = gender; }

     /* Methods */
     createUser() {
         db.insertUser({
             'firstName'     : this.fname,
             'lastName'      : this.lname,
             'age'           : this.age,
             'email'         : this.email,
             'password'      : this.password,
             'userAvatar'    : this.avatar,
             'gender'        : this.gender
         })
         .then(() => {
             console.log(this);
             return this;
         })
         .catch(error => {
             if (error.code == 'ER_DUP_ENTRY' && error.errno === 1062) throw new Error('This email is allready in use')
             else throw error;
         })
     }
    
     /* Validations */
    

    }

    module.exports = User;

  3. Controller

    const newUser = new User("fname", "lname", 22, "ema2121il", "password", "avatar", "gender"); newUser.createUser(); res.send(newUser)

I need to find a way to pass the validations errors, or the duplicate error from the point 2 (Object class) to the controller.

Please how can I do this?

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

So, if your goal is to return data to the express controller (from the class). The best way is to utilize the Promise Library. So your createUser function should look like this:

 createUser() {
   return new Promise ((resolve, reject) =>  {
       db.insertUser({
         'firstName'     : this.fname,
         'lastName'      : this.lname,
         'age'           : this.age,
         'email'         : this.email,
         'password'      : this.password,
         'userAvatar'    : this.avatar,
         'gender'        : this.gender
       })
       .then(() => {
         console.log(this);
         this.runValidations()
         return resolve(this);
     })
     .catch(error => {
         if (error.code == 'ER_DUP_ENTRY' && error.errno === 1062) {
            return reject('This email is already in use')
         } else {
            return reject();
          } 
     })
   });
 }

Then to utilize it from your controller, utilize async/await to utilize the method.

//The Controller Code

app.get('/create-user', async(req, res) =>  {
    const user = new User(req.body) // Assuming this is how you're instantiating class
    try {
       const newUser = await user.createUser();
       console.log("User is Created");
    } catch (err) {
       //Your Error will be available here.
       console.log("Your Error: ", err)
    }
    

})

This should get you what you need :)

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs