How to call a function that return the result of mysql query to send it back in a Express.js result?

Viewed 142

How to call a function that return the result of MySQL query to send it back in a Express.js result?

I try to export some of my sql query in individual function to clean up and remove duplicate code. I try with async await function, but it did not work.

How clean this code? Thanks

import { Request, Response } from 'express'
import { mysqlConnection } from '../config/mysql.config'
import { users } from '../models/users.models'
export class AuthController {
  constructor() { }


  // I want to avoid this embedded callbacks function
  public signin(req: Request, res: Response) {
    var user: users = req.body
    var insUser = [
      user.userEmail,
      user.userFirstName,
      user.userLastName,
      user.userEmail,
      //hash password
      // user.userPassword
    ]
    mysqlConnection.pool.getConnection((err, connection) => {
      connection.query('SELECT * FROM tblusers where userEmail = ? OR userUserName = ?', [user.userEmail, user.userUsername], (err, row: users[]) => {
        if (err) throw err;
        if (row.length) {
          return res.status(400).json({ errors: { msg: "user exist already", status: 'signin-error' } })
        }
        //addUserInDB
        connection.query('INSERT INTO tblusers (userUserName, userFirstName, userLastName, userEmail, userPassword) VALUES (? ,?, ?, ?, ?)', insUser, (err, row) => {
          if (err) throw err;
          //get userFormDB
          connection.query('SELECT userId, userUsername, userFirstName, userLastName, userEmail, userPassword, webrName FROM tblusers INNER JOIN tblweblroles ON tblusers.tblWeblroles_webrId = tblweblroles.webrId where userEmail = ?', [user.userEmail], (err, row: users[], fields) => {
            if (err) throw err
            connection.release();
            var firstUser = row[0]
            var user = {
              userId: firstUser.userId,
              userUsername: firstUser.userUsername,
              userFirstName: firstUser.userFirstName,
              userLastName: firstUser.userLastName,
              userEmail: firstUser.userEmail,
              userUpdateAt: firstUser.userUpdateAt,
              userCreatedAt: firstUser.userCreatedAt,
              webrName: firstUser.webrName
            }
            res.status(200).json(user);
          })
        })
      })
    })
  }

  //test
  private getUsers() {
    console.log('test')
    mysqlConnection.pool.query('SELECT * FROM webapp.tblusers;', (err: any, row: any) => {
      if (err) throw err
      console.log('row: ' + row)
      return row
    })
  }
  public async login(req: Request, res: Response) {
    console.log('test1')
    try {
      var users = await this.getUsers()
      console.log('users:' + users)
      res.json(users);
    } catch (error) {
      res.json(error);
    }
  };
}
1 Answers
export class AuthController {
  constructor() {
  }

  public async login(req: Request, res: Response) {
    var users: any = await AuthController.getUsers()
    res.json(users)
  };


  public static getUsers(): Promise<any> {
    console.log('test')
    return new Promise(resolve => {
      mysqlConnection.pool.query('SELECT * FROM webapp.tblusers;', (err: any, row: any) => {
        if (err) throw err
        resolve(row)
      })
    });
  }
}
Related