-
-
Save streamich/6175853840fb5209388405910c6cc04b to your computer and use it in GitHub Desktop.
import λ from "apex.js"; | |
import { Pool } from "pg"; | |
// connection details inherited from environment | |
const pool = new Pool({ | |
max: 1, | |
min: 0, | |
idleTimeoutMillis: 120000, | |
connectionTimeoutMillis: 10000 | |
}); | |
export default function λ(async (event, context) => { | |
// https://github.com/brianc/node-postgres/issues/930#issuecomment-230362178 | |
context.callbackWaitsForEmptyEventLoop = false; // !important to reuse pool | |
const client = await pool.connect(); | |
try { | |
await client.query("SELECT NOW()"); | |
} finally { | |
// https://github.com/brianc/node-postgres/issues/1180#issuecomment-270589769 | |
client.release(true); | |
} | |
}); |
Am i suppose to create pool for each lambda function ?
Considering Password and connection details shouldn't be exposed in environment variables, I wouldn't follow this example. Please keep your connection (sensitive information) in a Secret manager and pull them in-code directly to avoid any exposition.
When you create a RDS Instance, AWS automatically save the connection details in a Secret Manager variable.
Considering Password and connection details shouldn't be exposed in environment variables, I wouldn't follow this example. Please keep your connection (sensitive information) in a Secret manager and pull them in-code directly to avoid any exposition.
When you create a RDS Instance, AWS automatically save the connection details in a Secret Manager variable.
Is indeed the right way to do it, but as the pg client needs these information to connect, and to get these info you need an async call to secret manager how do you pass them to the new Pool( config )??, I'm in the same situation as the example in the main post, lambda and pool pg client
This is perfect.
For anyone that may work with this, please don't forget:
finally{
client.release();
}
Without that, after ~10 requests, your Lambda will throw an error.
This one worked for me!
AWS Lambda -> Node.js 16
AWS RDS -> PostgreSQL 14
NPM dependency "pg" 8.7.0
Env variables:
PGHOST=xxx
PGUSER=xxx
PGPASSWORD=xxx
PGDATABASE=xxx
PGSSLMODE=require
index.js
Execution Results