Skip to content

Commit 6c5dd84

Browse files
Add files via upload
1 parent 81ff490 commit 6c5dd84

3 files changed

Lines changed: 248 additions & 0 deletions

File tree

index.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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+

package-lock.json

Lines changed: 163 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "lambda-crud",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"keywords": [],
10+
"author": "",
11+
"license": "ISC",
12+
"type": "commonjs",
13+
"dependencies": {
14+
"pg": "^8.16.3"
15+
}
16+
}

0 commit comments

Comments
 (0)