【发布时间】:2021-03-16 04:21:18
【问题描述】:
我正在尝试使用 node.js lambda 函数将记录插入 RDS Postgres。我不知道它是否连接到数据库。它确实插入了 3 条记录,然后什么也没有。没有任何内容被写入日志。以下是我的代码:
'use strict';
const { Client } = require('pg') ;
const client = new Client();
client.connect();
exports.handler = async function(event, context) {
var response;
if (event.Records) {
for (let record of event.Records) {
var rec = JSON.parse(JSON.stringify(record.body));
var test = JSON.parse(rec);
console.log("test id:" + test.id);
const queryString = {
text: "INSERT INTO public.order VALUES ($1, $2, $3, $4)",
values: [test.id, test.email, test.total_price, test.token],
};
try{
const result = await client.query(queryString);
console.log(result.rowCount);
response = result.rowCount;
}
catch (err) {
console.log(err.stack);
}
}
client.end();
}
return response;
};
日志输出为:
INFO 测试 ID:820982911946154500
INFO 错误:客户端已关闭且无法在 /opt/nodejs/node_modules/pg/lib/client.js:570:27 at processTicksAndRejections (internal/process/task_queues.js:79:11) 处查询
感谢任何帮助。谢谢。
【问题讨论】:
-
您确定
event.Records的计算结果为真吗? -
@Daniel Farrell - 是的,它确实评估为真。它正在处理来自 SQS 的记录。我正在尝试处理来自 SQS 的消息/记录并将其插入数据库。所以 test.id 具有正确的值。问题是将其插入数据库。
-
有趣的是您的控制台日志消息没有显示在日志输出中
-
是的,因为我上面复制的日志来自我从控制台调用 lambda 函数时的日志。当我测试整个序列(即从我的数据源到 API Gateway -> SQS -> Lambda 函数)时,它实际上显示了正确的 id。从 SQS 复制日志:
-
来自 SQS 的日志确实显示错误 - 我的错! - INFO 测试 id:820982911946154500 INFO 错误:客户端已关闭且无法在 /opt/nodejs/node_modules/pg/lib/client.js:570:27 在 processTicksAndRejections (internal/process/task_queues.js:79:11) 处查询
标签: node.js postgresql lambda aws-lambda amazon-rds