I have a NodeJS lambda function that uses the mysql library for selecting data and retrieve it as a result. It gets triggered via an API Gateway http call.
But I can't seem to find a way to return the result of the query as the response of the call.
This is the sample code:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const mysql = require('mysql');
const con = mysql.createConnection({
host: process.env.RDS_HOSTNAME,
user: process.env.RDS_USERNAME,
password: process.env.RDS_PASSWORD,
port: process.env.RDS_PORT,
database: process.env.RDS_DATABASE,
});
const tableName = 'fit_guide';
export const handler = async (event, context, callback) => {
let response = {};
const routeKey = event.routeKey;
let sql = `SELECT * FROM ${tableName}`;
con.query(sql, function (error, results, fields) {
if (error) throw error;
// THIS DOES PRINT THE RESULTS FROM THE DATABASE TABLE
console.log('******** ', results);
// THIS DOESN'T RETURN
response = {
statusCode: 200,
success: true,
results,
};
callback(null, JSON.stringify(response));
return response;
});
con.end();
// THIS RETURNS AN EMPTY OBJECT {} (initial value)
callback(null, JSON.stringify(response));
return response;
};
How can I return the response inside the query execution rather than the initial value of the object?