Create a Node.js script that listens for AWS Lambda events, processes incoming JSON payloads, and inserts them into a PostgreSQL database. Include error handling and logging mechanisms.
PLAINFORMAT
// Import required modules
const { Client } = require('pg');
const AWS = require('aws-sdk');

// Set up AWS credentials
AWS.config.update({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: process.env.AWS_REGION,
});

// Configure the PostgreSQL client
const client = new Client({
  host: process.env.PG_HOST,
  port: process.env.PG_PORT,
  user: process.env.PG_USER,
  password: process.env.PG_PASSWORD,
  database: process.env.PG_DATABASE,
});

// Connect to the PostgreSQL database
client.connect((err) => {
  if (err) {
    console.error('Failed to connect to the PostgreSQL database:', err);
    process.exit(1);
  }
  console.log('Connected to the PostgreSQL database');
});

// Lambda function handler
exports.handler = async (event, context) => {
  // Log the event payload
  console.log('Received event:', JSON.stringify(event, null, 2));

  try {
    // Loop through records in the event payload
    for (const record of event.Records) {
      // Parse the JSON payload
      const payload = JSON.parse(record.body);

      // Insert the payload into the PostgreSQL database
      await insertPayload(payload);
    }

    // Return a successful response
    return {
      statusCode: 200,
      body: JSON.stringify({ message: 'Payloads processed successfully' }),
    };
  } catch (error) {
    console.error('Error processing payloads:', error);

    // Return an error response
    return {
      statusCode: 500,
      body: JSON.stringify({ message: 'An error occurred while processing payloads' }),
    };
  }
};

// Function to insert the payload into the PostgreSQL database
async function insertPayload(payload) {
  try {
    // Define the SQL query and values
    const query = 'INSERT INTO your_table_name (column1, column2, ...) VALUES ($1, $2, ...)';
    const values = [payload.column1, payload.column2, ...];

    // Execute the query
    await client.query(query, values);

    console.log(`Inserted payload with ID ${payload.id} into the database`);
  } catch (error) {
    console.error(`Failed to insert payload with ID ${payload.id}:`, error);
    throw error;
  }
}