-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
96 lines (82 loc) · 3.02 KB
/
index.js
File metadata and controls
96 lines (82 loc) · 3.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const { Client } = require('pg');
exports.handler = async (event) => {
// Force IPv4 for SSH tunnel
const client = new Client({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: 5432,
ssl: { rejectUnauthorized: false } // IMPORTANT for RDS
});
console.log('Connecting to PostgreSQL on host:', client.host); // debug log
await client.connect();
const method = event.httpMethod;
let body = {};
let statusCode = 200; // default
try {
if (method === 'POST') {
const data = JSON.parse(event.body);
const res = await client.query(
'INSERT INTO users(name, email) VALUES($1, $2) RETURNING *',
[data.name, data.email]
);
body = res.rows[0];
statusCode = 201; // Created
} else if (method === 'GET') {
const id = event.pathParameters ? event.pathParameters.id : null;
const res = id
? await client.query('SELECT * FROM users WHERE id=$1', [id])
: await client.query('SELECT * FROM users');
if (id) {
if (!res.rows[0]) {
body = { message: 'User not found' };
statusCode = 404; // Not found
} else {
body = res.rows[0];
statusCode = 200;
}
} else {
body = res.rows;
statusCode = 200;
}
} else if (method === 'PUT') {
const id = event.pathParameters.id;
const data = JSON.parse(event.body);
const res = await client.query(
'UPDATE users SET name=$1, email=$2 WHERE id=$3 RETURNING *',
[data.name, data.email, id]
);
if (!res.rows[0]) {
body = { message: 'User not found' };
statusCode = 404;
} else {
body = res.rows[0];
statusCode = 200;
}
} else if (method === 'DELETE') {
const id = event.pathParameters.id;
const res = await client.query('DELETE FROM users WHERE id=$1 RETURNING *', [id]);
if (!res.rows[0]) {
body = { message: 'User not found' };
statusCode = 404;
} else {
body = { message: 'Deleted successfully' };
statusCode = 200;
}
} else {
body = { message: 'Unsupported method' };
statusCode = 400;
}
} catch (err) {
body = { error: err.message };
statusCode = 500;
} finally {
await client.end(); // always close the connection
}
return {
statusCode,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
};
};