I am currently creating an AWS Lambda resolver that utilizes Nodejs mysql library. Right now, my lambda is capable of executing a query to the database during the first invocation. However, on the subsequent invocations the error "Cannot enqueue Query after invoking quit" occurs. I am aware that it is something to do with the connection to the database but if I am not wrong, 'connection.query' should be making an implicit connection to the database. I am also calling the 'connection.end' within the callback. Could someone lend me a helping hand on this one?
Here is the Lambda index.js code:
/* Amplify Params - DO NOT EDIT
API_SIMPLETWITTERCLONE_GRAPHQLAPIENDPOINTOUTPUT
API_SIMPLETWITTERCLONE_GRAPHQLAPIIDOUTPUT
API_SIMPLETWITTERCLONE_GRAPHQLAPIKEYOUTPUT
AUTH_SIMPLETWITTERCLONEB1022521_USERPOOLID
ENV
REGION
Amplify Params - DO NOT EDIT */
const mysql = require("mysql");
// const util = require("util");
const config = require("./config.json");
const connection = mysql.createConnection({
host: config.dbhost,
user: config.dbuser,
password: config.dbpassword,
database: config.dbname,
});
// resolvers
const resolvers = {
Query: {
getAllUser: (event) => {
return getAllUser();
},
},
};
function executeQuery(sql, params) {
return new Promise((resolve, reject) => {
const queryCallback = (error, results) => {
if (error) {
console.log("Error occured during query: " + error.message);
connection.destroy();
reject(error);
} else {
console.log("Connected to database and executed query");
console.log("Results:", results);
connection.end((err) => {
if (err) {
console.log("there was an error closing database:" + err.message);
}
console.log("database closed");
resolve(results);
});
}
};
if (params) {
connection.query(sql, [...params], (error, results) => {
queryCallback(error, results);
});
} else {
connection.query(sql, (error, results) => {
queryCallback(error, results);
});
}
});
}
async function getAllUser() {
const sql = "SELECT * FROM User";
try {
const users = await executeQuery(sql);
return users;
} catch (error) {
throw error;
}
}
exports.handler = async (event) => {
// TODO implement
console.log("event", event);
console.log('DB connection var', connection);
const typeHandler = resolvers[event.typeName];
if (typeHandler) {
const resolver = typeHandler[event.fieldName];
if (resolver) {
try {
return await resolver(event);
} catch (error) {
throw error;
}
}
}
throw new Error("Resolver not found");
};
Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW
Comments
Post a Comment