我使用 ClaudiaJS 部署无服务器 API(Lambda + API Gateway)。在我的 API 中,我使用 pg-pool 访问 RDS Postgres。
我做了什么:
在 app.js 中
var ApiBuilder = require('claudia-api-builder'),
api = new ApiBuilder();
module.exports = api;
var Pool = require('pg-pool');
api.get("/list", function (request) {
var dbconnect = {
user: ‘xxxx’, //env var: PGUSER
database: ‘xxxx’, //env var: PGDATABASE
password: ‘xxx’, //env var: PGPASSWORD
host: ‘xxxxxxxxxx.eu-west-1.rds.amazonaws.com', // Server hosting the postgres database
port: 5432, //env var: PGPORT
max: 1,
min: 0,
idleTimeoutMillis: 300000,
connectionTimeoutMillis: 1000
};
var pool = new Pool(dbconnect)
var sql = ‘Select …’
pool.query(sql, function (err, result) {
console.log('Lambda :: execute query ');
var resp = new Object();
var jsonArr = []; // Populate the result
console.log('Lambda :: result :: ' + JSON.stringify(result));
return JSON.stringify(result)
});
}
什么问题: 它不会返回任何内容,Cloudwatch 也不会显示任何错误。我用谷歌搜索了一下,人们说它没有包含在 Promise 中。我的问题是如何在这种情况下将 pg-pool 包装在 Promise 中。
如有任何建议,我们将不胜感激。谢谢
****更新****
我尝试在池中使用 promise
pool.connect().then(client => {
client.query(sql).then(res => {
client.release()
console.log('Result:', res.rows[0])
return JSON.stringify(res.rows[0]);
})
.catch(e => {
client.release()
console.error('query error', e.message, e.stack)
})
})
我收到来自 CloudWatch 的错误:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Connection terminiated due to connection timeout
最佳答案
看起来你可以从 pool.query
得到一个 promise :
pg-pool supports a fully promise-based api for acquiring clients
https://github.com/brianc/node-pg-pool#acquire-clients-with-a-promise
然后您可以链接 promise 以返回 JSON:
return pool.query(sql).then(function (result) {
console.log('Lambda :: execute query ');
var resp = new Object();
var jsonArr = []; // Populate the result
console.log('Lambda :: result :: ' + JSON.stringify(result));
return JSON.stringify(result)
}, function(error){
//handle error here
console.error(error);
});
关于node.js - ClaudiaJS 和 pg-pool : how to wrap in promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46452737/