condition check lambda

This commit is contained in:
jackiettran
2026-01-13 17:14:19 -05:00
parent 2ee5571b5b
commit f5fdcbfb82
30 changed files with 14293 additions and 461 deletions

View File

@@ -0,0 +1,89 @@
const { Pool } = require("pg");
let pool = null;
/**
* Get or create a PostgreSQL connection pool.
* Uses connection pooling optimized for Lambda:
* - Reuses connections across invocations (when container is warm)
* - Small pool size to avoid exhausting database connections
*
* Expects DATABASE_URL environment variable in format:
* postgresql://user:password@host:port/database
*/
function getPool() {
if (!pool) {
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error("DATABASE_URL environment variable is required");
}
pool = new Pool({
connectionString,
// Lambda-optimized settings
max: 1, // Single connection per Lambda instance
idleTimeoutMillis: 120000, // 2 minutes - keep connection warm
connectionTimeoutMillis: 5000, // 5 seconds to connect
});
// Handle pool errors
pool.on("error", (err) => {
console.error("Unexpected database pool error:", err);
pool = null; // Reset pool on error
});
}
return pool;
}
/**
* Execute a query with automatic connection management.
* @param {string} text - SQL query text
* @param {Array} params - Query parameters
* @returns {Promise<object>} Query result
*/
async function query(text, params) {
const pool = getPool();
const start = Date.now();
try {
const result = await pool.query(text, params);
const duration = Date.now() - start;
console.log(JSON.stringify({
level: "debug",
message: "Executed query",
query: text.substring(0, 100),
duration,
rows: result.rowCount,
}));
return result;
} catch (error) {
console.error(JSON.stringify({
level: "error",
message: "Query failed",
query: text.substring(0, 100),
error: error.message,
}));
throw error;
}
}
/**
* Close the connection pool (for cleanup).
* Call this at the end of Lambda execution if needed.
*/
async function closePool() {
if (pool) {
await pool.end();
pool = null;
}
}
module.exports = {
getPool,
query,
closePool,
};

View File

@@ -0,0 +1,109 @@
const { query } = require("./connection");
/**
* Get rental with all related details (owner, renter, item).
* @param {string} rentalId - UUID of the rental
* @returns {Promise<object|null>} Rental with relations or null if not found
*/
async function getRentalWithDetails(rentalId) {
const result = await query(
`SELECT
r.id,
r."itemId",
r."renterId",
r."ownerId",
r."startDateTime",
r."endDateTime",
r."totalAmount",
r.status,
r."createdAt",
r."updatedAt",
-- Owner fields
owner.id AS "owner_id",
owner.email AS "owner_email",
owner."firstName" AS "owner_firstName",
owner."lastName" AS "owner_lastName",
-- Renter fields
renter.id AS "renter_id",
renter.email AS "renter_email",
renter."firstName" AS "renter_firstName",
renter."lastName" AS "renter_lastName",
-- Item fields
item.id AS "item_id",
item.name AS "item_name",
item.description AS "item_description"
FROM "Rentals" r
INNER JOIN "Users" owner ON r."ownerId" = owner.id
INNER JOIN "Users" renter ON r."renterId" = renter.id
INNER JOIN "Items" item ON r."itemId" = item.id
WHERE r.id = $1`,
[rentalId]
);
if (result.rows.length === 0) {
return null;
}
const row = result.rows[0];
// Transform flat result into nested structure
return {
id: row.id,
itemId: row.itemId,
renterId: row.renterId,
ownerId: row.ownerId,
startDateTime: row.startDateTime,
endDateTime: row.endDateTime,
totalAmount: row.totalAmount,
status: row.status,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
owner: {
id: row.owner_id,
email: row.owner_email,
firstName: row.owner_firstName,
lastName: row.owner_lastName,
},
renter: {
id: row.renter_id,
email: row.renter_email,
firstName: row.renter_firstName,
lastName: row.renter_lastName,
},
item: {
id: row.item_id,
name: row.item_name,
description: row.item_description,
},
};
}
/**
* Get user by ID.
* @param {string} userId - UUID of the user
* @returns {Promise<object|null>} User or null if not found
*/
async function getUserById(userId) {
const result = await query(
`SELECT
id,
email,
"firstName",
"lastName",
phone
FROM "Users"
WHERE id = $1`,
[userId]
);
if (result.rows.length === 0) {
return null;
}
return result.rows[0];
}
module.exports = {
getRentalWithDetails,
getUserById,
};