ClaudiaJS and pg-pool: how to wrap in promise

399 views Asked by At

I use ClaudiaJS to deploy the serverless API (Lambda + API Gateway). In my API, I access to RDS Postgres using pg-pool.

What I have done:

In 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)
});
}

What problem: It doesn't return anything, and Cloudwatch also doesn't show any errors. I googled it, and people said it's not wrapped in Promise. My question is how to wrap pg-pool in Promise for this case.

Any suggestion is appreciated. Thanks

****Update****

I tried to use the promise in pool

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)
  })
})

I received error from CloudWatch:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Connection terminiated due to connection timeout

3

There are 3 answers

0
Phong Vu On BEST ANSWER

Thanks for your replies so far. After playing around the code and googling at weekend, I found the way to handle it, I leave the solution here for other if any.

var ApiBuilder = require('claudia-api-builder');
var pgp = require('pg-promise')();

api = new ApiBuilder();
module.exports = api;

api.get('/list', function (request) {

   var dbconnect = {
      user: ‘xxx’, //env var: PGUSER
      database: ‘xxx’, //env var: PGDATABASE
      password: ‘xxx’, //env var: PGPASSWORD
      host: ‘xxxx.rds.amazonaws.com', // Server hosting the postgres database
      port: 5432, //env var: PGPORT
   };

   var db = pgp(dbconnect);

   var sql = "SELECT * from table ...“;

   return db.any(sql).then(function (data) {

      pgp.end();

      console.log('Lambda :: params :: ' + JSON.stringtify(data));

      var resp = {
         name: data[0].name,
         serial_number: data[0].serial
      };

     return resp;
  })
   .catch(function (error) {
      console.log("Lambda :: Error: " + error);
      pgp.end();
  });
});

It works for me. Anyway, if anyone have a better idea, please also share it here.

4
gaheinrichs On

Looks like you can get a promise back from pool.query:

pg-pool supports a fully promise-based api for acquiring clients

https://github.com/brianc/node-pg-pool#acquire-clients-with-a-promise

Then you can chain the promise to return your 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);
});
2
Slobodan Stojanovic On

You need to return the promise. So:

return pool.connect().then(client => { // Return a promise
  return client.query(sql).then(res => { // Return promise again, if you omit this it will break promise chain
    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)
    throw e // Throw an error so Claudia can catch it
  })
})