|
| 1 | +onst { Client } = require('pg'); |
| 2 | + |
| 3 | +exports.handler = async (event) => { |
| 4 | + |
| 5 | +// Create a NEW client inside handler (not globally) |
| 6 | +const client = new Client({ |
| 7 | + host: process.env.DB_HOST, |
| 8 | + user: process.env.DB_USER, |
| 9 | + password: process.env.DB_PASSWORD, |
| 10 | + database: process.env.DB_NAME, |
| 11 | + port: 5432, |
| 12 | + ssl: { |
| 13 | + rejectUnauthorized: false // IMPORTANT for RDS |
| 14 | + } |
| 15 | + }); |
| 16 | + |
| 17 | + await client.connect(); |
| 18 | + |
| 19 | + const method = event.httpMethod; |
| 20 | + let body = {}; |
| 21 | + |
| 22 | + try { |
| 23 | + if (method === 'POST') { |
| 24 | + const data = JSON.parse(event.body); |
| 25 | + const res = await client.query( |
| 26 | + 'INSERT INTO users(name, email) VALUES($1, $2) RETURNING *', |
| 27 | + [data.name, data.email] |
| 28 | + ); |
| 29 | + body = res.rows[0]; |
| 30 | + |
| 31 | + } else if (method === 'GET') { |
| 32 | + const id = event.pathParameters ? event.pathParameters.id : null; |
| 33 | + const res = id |
| 34 | + ? await client.query('SELECT * FROM users WHERE id=$1', [id]) |
| 35 | + : await client.query('SELECT * FROM users'); |
| 36 | + body = res.rows; |
| 37 | + |
| 38 | + } else if (method === 'PUT') { |
| 39 | + const id = event.pathParameters.id; |
| 40 | + const data = JSON.parse(event.body); |
| 41 | + const res = await client.query( |
| 42 | + 'UPDATE users SET name=$1, email=$2 WHERE id=$3 RETURNING *', |
| 43 | + [data.name, data.email, id] |
| 44 | + ); |
| 45 | + body = res.rows[0]; |
| 46 | + |
| 47 | + } else if (method === 'DELETE') { |
| 48 | + const id = event.pathParameters.id; |
| 49 | + await client.query('DELETE FROM users WHERE id=$1', [id]); |
| 50 | + body = { message: 'Deleted successfully' }; |
| 51 | + |
| 52 | + } else { |
| 53 | + body = { message: 'Unsupported method' }; |
| 54 | + } |
| 55 | + |
| 56 | + } catch (err) { |
| 57 | + body = { error: err.message }; |
| 58 | + |
| 59 | + } finally { |
| 60 | + await client.end(); // always close the connection |
| 61 | + } |
| 62 | + |
| 63 | + return { |
| 64 | + statusCode: 200, |
| 65 | + headers: { "Content-Type": "application/json" }, |
| 66 | + body: JSON.stringify(body) |
| 67 | + }; |
| 68 | +}; |
| 69 | + |
0 commit comments