Undefined result - Getting data from phpmyadmin using dialogflow - mysql

I'm working on a project to retrieve data from phpmyadmin by using Dialogflow.
I've been following a tutorial on YouTube.
However, the results after performing a very simple query is undefined.
Here is my code
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const mysql = require('mysql');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function connectToDatabase(){
const connection = mysql.createConnection({
host: '***.***.***.***',
user: '*************',
password: '*********',
database: '****************'
});
return new Promise((resolve, reject) => {
connection.connect();
resolve(connection);
});
}
function queryDatabase(connection){
return new Promise((resolve, reject) => {
connection.query('SELECT * FROM Data', (error, results, fields) => {
resolve(results);
});
});
}
function handleReadDB(agent){
return connectToDatabase()
.then(connection => {
return queryDatabase(connection)
.then(result => {
console.log(result);
connection.end();
});
});
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('ReadDB', handleReadDB);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
});
the results show something like this
3:10:29.505 PM
outlined_flag
dialogflowFirebaseFulfillment
Function execution took 1296 ms, finished with status code: 200
3:10:29.503 PM
info
dialogflowFirebaseFulfillment
undefined
Please help

Related

MySQL async await db connection: TypeError: pool.query is not a function

require('dotenv').config()
const AWS = require('aws-sdk');
const ssm = new AWS.SSM({
region: 'us-east-1',
});
const mysql = require('mysql');
const pool = async () => await dbConnection();
async function key(param) {
const parameter = await ssm.getParameter({
Name: param,
WithDecryption: true
})
.promise()
.catch((err) => {
console.error('Failed getting parameter');
console.error(err);
});
const data = parameter.Parameter.Value;
console.log(data);
return data;
}
async function dbConnection() {
const pool = mysql.createPool({
connectionLimit: 10,
host: await key("host-d"),
user: await key("user-d"),
password: await key("pw-d"),
database: await key("db-d")
});
return pool;
};
async function executeSQL(sql, params) {
return new Promise(function (resolve, reject) {
pool.query(sql, params, function (err, rows, fields) {
if (err) throw err;
resolve(rows);
});
});
}
Trying to get credentials from AWS before creating mysql pool connection. I keep getting the follwing error "TypeError: pool.query is not a function" when executeSQL is called not sure why

How can I resolve a promised mysql query in express.js?

I'm trying to use the npm package promise-mysql and return json data (or a string doesn't matter) but I'm having issues following the promise chain with await/async.
With the current code i'm receiving Promise { undefined } in the console.log I have right before the response to the user. The response just sends nothing to the user and closes it. Can anyone point in the right direction of how to debug this?
index.js
app.get("/", async (req, res) => {
console.log( Promise.resolve(await getLogs()) )
res.send(await getLogs());
});
mysql.js
const mysql = require("promise-mysql");
let pool;
async function startDatabasePool() {
pool = await mysql.createPool({
connectionLimit: 10,
host: "xxx",
user: "xxx",
password: "xxx",
database: "xxx"
});
}
async function getDatabasePool() {
if (!pool) await startDatabasePool();
return pool;
}
module.exports = {
getDatabasePool,
startDatabasePool
};
users.js
const { getDatabasePool } = require("./mysql");
async function getLogs() {
let pool = await getDatabasePool();
pool.query("SELECT * from logs order by logdate desc", function(
error,
results,
fields
) {
if (error) throw error;
return JSON.stringify(results);
});
}
module.exports = {
getLogs
};
index.js
app.get("/", async (req, res) => {
const result = await getLogs();
res.send(result);
});
mysql.js
const mysql = require("promise-mysql");
let pool;
module.exports.startDatabasePool = async () => {
pool = await mysql.createPool({
connectionLimit: 10,
host: "xxx",
user: "xxx",
password: "xxx",
database: "xxx"
});
}
module.exports.getDatabasePool = async () => {
if (!pool) await startDatabasePool();
return pool;
}
// convert function as promise
module.exports.executeQuery = async(params) => {
return new Promise((resolve, reject) => {
pool.query(params, function (error, result, fields) {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
};
users.js
const { executeQuery } = require("./mysql");
module.exports.getLogs = async () => {
return await executeQuery("SELECT * from logs order by logdate desc");
}
First I'd try it like:
app.get("/", async (req, res) => {
let logs = await getLogs()
console.log(logs)
res.send(logs);
});
I hope it helps!

Lambda function MySQL result not working on NodeJs 8.10

I have a code in Node 6.10 and it is working...
But If I convert it to Node 8.10 it's not working
var mysql = require("mysql");
var connection = mysql.createConnection({
host: " localhost",
user: "root",
password: "",
database: "parser_db"
});
exports.handler = async event => {
connection.connect();
let response = {
statusCode: 400,
body: { Method: "Invalid", event }
};
var readTable = "SELECT * FROM documents where id = " + mysql.escape(1);
connection.query(readTable, function(err, results, fields) {
if (err) throw err;
else {
response = {
statusCode: 200,
body: { results }
//body: { results }
};
console.log(response);
return response;
}
});
};
Can some one please help me to detect the problem. It is also not working if I do the MySQL query in separate file and return the result set.
Note : If I print the result using console.log(response) instead returning it's
showing the correct result.
The problem is that you are returning response from within the connection.query() callback function. That makes response the return value for the callback function, not the return value for the outer Lambda function.
One way to restructure this code is as follows:
exports.handler = async (event) => {
connection.connect();
return new Promise((resolve, reject) => {
const readTable = `SELECT * FROM documents where id = ${mysql.escape(1)}`;
connection.query(readTable, (err, results, fields) => {
if (err) {
reject(err);
} else {
resolve({statusCode: 200, body: {results}});
}
});
});
};
In addition to #jarmod's answer, You can also use the util.promisify method to promisify connection.query so that you can use the await keyword, to make the code simpler
const util = require('util');
exports.handler = async (event) => {
connection.connect();
const readTable = `SELECT * FROM documents where id = ${mysql.escape(1)}`;
const connQueryPromisified = util.promisify(connection.query).bind(connection);
const result = await connQueryPromisified(readTable);
return {statusCode: 200, body: {results}};
};

How do I pass mysql database content to a different page?

I am trying to display my database content to an ejs web page. However, I am running into a problem when trying to pass the content between pages.
I have a JavaScript page "store.js" which has the server running:
store.js-
var express = require('express');
var dbcon = require('./app/db/databaseconnection');
//var path = require('path');
//dbcon.connection;
var app = express();
var router = express.Router();
dbcon.connect();
console.log(dbcon.getproducts());
//var filepath = path.join(__dirname, '../../views/')
var filepath = __dirname + '/views/';
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use('/', router);
router.get('/', (request, response) => response.render(filepath + 'index', { page_name: 'home' }));
router.get('/store', (request, response) => response.render(filepath + 'store', { page_name: 'store' }));
router.get('/about', (request, response) => response.render(filepath + 'about', { page_name: 'about' }));
router.get('/contact', (request, response) => response.render(filepath + 'contact', { page_name: 'contact' }));
router.get('/build', (request, response) => response.render(filepath + 'build/build'));
router.get('/learn', (request, response) => response.render(filepath + 'learn/learn'));
app.use('*', (request, response) => response.render(filepath + '404', { page_name: '404' }));
app.listen(3000, () => console.log("Server running at Port 3000"));
Then I have a JavaScript page which includes the database connection:
databaseconnection.js-
var mysql = require('mysql');
var connection = mysql.createConnection(conObject = {
host: "localhost",
user: "root",
password: "LOTOS123l",
database: "dbComputerStore"
});
module.exports = {
connect: () =>
{
connection.connect((error) => {
if (error) throw error;
console.log(conObject.database + " connected!");
});
},
// The display method prints the returned result to the console.
// Change this to return the result. Maybe a toString() ?
getproducts: () => {
/*var result = */connection.query('SELECT * FROM products', (error, result) => {
return result;
//return result;
// console.log(result);
// How to get certain properties
// console.log(result[0].brand);
// console.log(result[0].series);
// console.log(result[0].model);
});
//return result.result;
},
createdb: () => {
},
createtable: () => {
},
populatetable: () => {
}
}
So on the store.js page I have the console.log(dbcon.getproducts()); Which I was hoping would display the database content of the "products" table. However I keep getting undefined. Basically, I can't get it to pass from the database connection page to the store.js page.
If I get this to work, my next step would be to find a way to display the products table to an ejs page. I've been trying to solve this for a while now so any help would be appreciated! Thank You!
Following up my comments, here's how you can modify databaseconnection.js module to use a connection pool and return query results via Promises:
Note: the code is mostly untested
const mysql = require("mysql");
const pool = mysql.createPool({
connectionLimit: 10, // adjust this according to your needs
host: "localhost",
user: "root",
password: "LOTOS123l",
database: "dbComputerStore"
});
module.exports = {
// you don't need the connect method anymore
getProducts: () => new Promise((resolve, reject) => {
pool.query("SELECT * FROM products", (error, results, fields) => {
if (error) {
reject(error);
} else {
resolve(results);
}
});
}),
// ...
};
then in store.js, you can do:
const dbcon = require('./app/db/databaseconnection');
dbcon.getProducts()
.then(results => {
console.log(results);
})
.catch(err => {
console.error(err);
});
// or you could use async/await syntax:
const asyncFn = async () => {
try {
const results = await dbcon.getProducts();
console.log(results);
} catch (ex) {
console.error(err);
}
};
asyncFn();

If I console.log my results it shows up, but if I return it it doesn't

My return result doesn't make it all the way back to API endpoint.
Do you see what I'm doing wrong?
app.js
const express = require('express');
const app = express();
app.use(express.static('client'));
var GetContracts = require('./contractsService');
app.get('/contracts', async (req, res) => {
var results = await GetContracts.get();
console.log(results);
res.send(results);
});
module.exports = app;
contractsService.js
var mysql = require('mysql');
const config = require('./config')
var con = mysql.createConnection({
host: config.HOST,
user: config.USER,
password: config.PASSWORD,
database: config.DATABASE
});
exports.get = function () {
con.connect(function (err) {
if (err) {
throw new Error('Error by Rodney')
};
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) {
throw new Error('Error by Rodney')
};
return result;
//console.log(result); //works
});
});
}
query method accepts error-first callback that isn't affected by returned value. GetContracts.get doesn't return a promise, and awaiting won't do anything.
It should be promisified in order to be used in promise control flow:
exports.get = function () {
return new Promise((resolve, reject) => {
con.connect(function (err) {
if (err) {
reject(new Error('Error by Rodney'))
};
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) {
reject(new Error('Error by Rodney'));
} else
resolve(result);
});
});
});
}
Or preferably, use existing promise-based MySQL library like promise-mysql, something like:
var mysql = require('promise-mysql');
const conPromise = mysql.createConnection({
host: config.HOST,
user: config.USER,
password: config.PASSWORD,
database: config.DATABASE
});
exports.get = async () => {
const con = await conPromise;
const result = await con.query("SELECT * FROM " + config.DATABASE + ".Contracts");
return result;
};