I'm trying to build an API using AWS Lambda & 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.
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.
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.
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.
const {Client} = require('pg');
var response
exports.handler = async (event) => {
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) => {
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;
};
client.connect();intry/catchand confirm the connection is correctly established since if not this can cause the issues you are describing