Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda