title: How do I get a node.js lambda function to write to postgresql and return the error/response?
body: <p>I'm trying to build an API using AWS Lambda &amp; node.js which writes a record into a postgres database. I then want to return the response from the db back as the API response.</p>
  
  <p>I can get write action to work from my laptop, but not as a Lambda function. It just doesn't seem to execute the client.query function. I think this is because the event.handler runs asynchronously but I'm stuck on how to make this work.</p>
  
  <p>Secondly I want to pass the res or err back out of the client.query function so I can return it as the API response. I can't figure out how to get those out of the query function even running locally.</p>
  
  <p>I thought declaring response at the start would make it global but whilst debugging it is undefined at the point where I'm trying to return it.</p>
  
  <pre><code>const {Client} = require('pg');
  
  var response
  
  exports.handler = async (event) =&gt; {
  
      const body = JSON.parse(event.body);
      const query = {
          text: "insert into testTwo (test) values($1)",
          values: [body.text],
      }
  
      const client = new Client({
          user: '',
          host: '',
          database: '',
          password: '',
          port: 5432,
      });
      client.connect();
  
      client.query(query, (err,res) =&gt; {
          console.log("Why doesn't this execute?");
          if (err) {
              response = {
                  statusCode: 400,
                  body: JSON.stringify(err)
              };
          } else {
              response = {
                  statusCode: 200,
                  body: JSON.stringify(res)
              };
          }
      client.end();
  
      });
  
      return response;
  
  };
  </code></pre>