我目前正在创建一个利用Nodejs mysql库的AWS Lambda解析器。现在,我的lambda能够在第一次调用期间执行对数据库的查询。但是,在随后的调用中,错误"无法在调用退出后排队查询"。发生。我知道这与数据库的连接有关,但如果我没有错的话,是"连接"。Query '应该隐式连接到数据库。我也称之为"连接"。在回调中结束。有人能在这件事上帮帮我吗?
下面是Lambda index.js代码:/* 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");
};
在第一次调用期间结束连接。因此,第二次调用不再具有该连接。
如果在模块导入过程中创建了connection
对象,不要在调用中.end()
它。
如果您希望在调用期间.end()
connection
对象,您必须在调用期间创建