0

I am trying to insert a record into RDS Postgres using node.js lambda function. I can't tell if it is connecting to the database or not. It did insert 3 records once and then nothing. Nothing is being written to the log. Below is my code:

'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;
};

The log output is:

INFO test id:820982911946154500

INFO Error: Client was closed and is not queryable at /opt/nodejs/node_modules/pg/lib/client.js:570:27 at processTicksAndRejections (internal/process/task_queues.js:79:11)

Any help is appreciated. Thanks.

mywn9
  • 107
  • 12
  • are you sure `event.Records` evaluates to true? – erik258 Dec 04 '20 at 05:03
  • @Daniel Farrell - Yes it does evaluate to true. It is processing a record from SQS. I am trying to process a message/record from SQS and insert it into DB. So test.id has the right value. The issue is inserting it into db. – mywn9 Dec 04 '20 at 05:55
  • interesting that your console log message doesn't show in the log output – erik258 Dec 04 '20 at 05:58
  • Yes because the log I copied above was from when I was invoked the lambda function from the console. It is in fact displaying the right id when I test the whole sequence i.e from my data source to API Gateway -> SQS - > Lambda function. Copying the log from SQS: – mywn9 Dec 04 '20 at 06:06
  • The log from SQS does show an error - my bad! - INFO test id:820982911946154500 INFO Error: Client was closed and is not queryable at /opt/nodejs/node_modules/pg/lib/client.js:570:27 at processTicksAndRejections (internal/process/task_queues.js:79:11) – mywn9 Dec 04 '20 at 06:14

1 Answers1

0

Resolved this after changing to pg.Pool() to manage the connections based on this post - Node.js - PostgreSQL (pg) : Client has already been connected. You cannot reuse a client

mywn9
  • 107
  • 12