在学习本教程之后,我试图设置一个AWS Lambda函数,该函数将使用Data API将SQL查询传递给AWS RDS Aurora Serverless MySQL数据库,并返回查询结果(大概是JSON)。
我下面使用的代码(参数存储为环境变量):
const AWS = require('aws-sdk')
const RDS = new AWS.RDSDataService()
exports.handler = async (event, context) => {
console.log(JSON.stringify(event, null, 2)) // Log the entire event passed in
// Get the sqlStatement string value
// TODO: Implement a more secure way (e.g. "escaping") the string to avoid SQL injection
var sqlStatement = event.sqlStatement;
// The Lambda environment variables for the Aurora Cluster Arn, Database Name, and the AWS Secrets Arn hosting the master credentials of the serverless db
var DBSecretsStoreArn = process.env.DBSecretsStoreArn;
var DBAuroraClusterArn = process.env.DBAuroraClusterArn;
var DatabaseName = process.env.DatabaseName;
const params = {
awsSecretStoreArn: DBSecretsStoreArn,
dbClusterOrInstanceArn: DBAuroraClusterArn,
sqlStatements: sqlStatement,
database: DatabaseName
}
try {
let dbResponse = await RDS.executeSql(params)
console.log(JSON.stringify(dbResponse, null, 2))
return JSON.stringify(dbResponse)
} catch (error) {
console.log(error)
return error
}
}
我从Lambda控制台(其中“ Bonds”是数据库中现有表的名称)运行以下测试:
{
"sqlStatement": "SELECT * FROM Bonds"
}
成功记录了我的测试,输出为空白{}
,并记录了以下错误信息:
INFO TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Request'
| property 'response' -> object with constructor 'Response'
--- property 'request' closes the circle
at JSON.stringify (<anonymous>)
at Runtime.exports.handler (/var/task/index.js:25:24)END
有人知道我如何使用此方法成功检索数据,和/或上述错误是什么意思?
RDS.executeSql(params)
不会返回您可以await
的承诺。它只是为您构造一个请求对象。
用await RDS.executeSql(params).promise()
代替,所以您可以获得想要的值。
参考: