0

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?

3
  • Currently, I cannot send the rejected response from the User class to the express response Commented Jan 20, 2022 at 18:26
  • the validation should be done in controller. i recommend joi library Commented Jan 20, 2022 at 18:39
  • Thanks. But what about the response from the promise? Commented Jan 20, 2022 at 18:40

1 Answer 1

1

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect. Thanks aloooot. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.