I want to get all the records from my table rol
, the query works when I execute it directly on the path, but putting the SQL query in an external file no longer returns the result, instead I get undefined
.
Database connection.
const { database } = require('./keys');
const mysql = require('mysql');
const { promisify } = require('util');
const pool = mysql.createPool(database);
pool.getConnection((err, con) => {
if (err) throw err;
console.log(`-> db status: ${con.state}`);
con.release();
return;
})
pool.query = promisify(pool.query);
module.exports = pool;
route.js
var express = require('express');
var router = express.Router();
let rolController = require('../controllers/rolController');
router.get('/', async (req, res) => {
let roles = await rolController.allRol();
console.log(roles);
res.send(roles);
})
module.exports = router;
The SQL query is in the following filerolController.js
let db = require('../database');
module.exports = {
allRol: (req, res) => {
db.query('SELECT * FROM rol where rol_state = 1', (err, row) => {
if (err) throw err;
return row;
})
}
}
I think the problem you have is in the file
rollController.js
that you do not return the result of the query, that is, if you return it but within the scope of the query to the database so it does not affect the scope of the functionallRol
, for that reason does not return anything. Since you are using the utilitypromisify
, which transforms callbacks into promises, I will use Async/Await to resolve those promises and return the result, capturing possible errors (an issue that you should watch out for if they occur).Here is the code that should work for you:
I hope that with this I have been able to help you solve your problem, in this case do not hesitate to ask.
Cheers
PS: in the file
router.js
you would not need to use Async/Await since you are not working with Promises at that moment: