-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (60 loc) · 1.78 KB
/
index.js
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
const express = require('express');
const { Pool } = require('pg');
const app = express();
const port = process.env.PORT || 3000;
// Database connection
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
// Middleware to parse JSON data
app.use(express.json());
// Function to create "Messages" table if it doesn't exist
async function createTableIfNotExists() {
try {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS Messages (
id SERIAL PRIMARY KEY,
name VARCHAR NOT NULL,
email VARCHAR NOT NULL,
message TEXT NOT NULL
)
`;
const client = await pool.connect();
await client.query(createTableQuery);
client.release();
console.log('Table "Messages" created or already exists.');
} catch (error) {
console.error('Error creating table:', error);
}
}
// Endpoint to handle POST requests
app.post('/messages', async (req, res) => {
try {
const { name, email, message } = req.body;
// Insert the data into the database
const insertQuery = `
INSERT INTO Messages (name, email, message)
VALUES ($1, $2, $3)
RETURNING *
`;
const values = [name, email, message];
const client = await pool.connect();
const result = await client.query(insertQuery, values);
client.release();
res.status(201).json(result.rows[0]);
} catch (error) {
console.error('Error storing data:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
// Start the server and create table before listening
(async () => {
try {
await createTableIfNotExists();
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
} catch (error) {
console.error('Error starting the server:', error);
}
})();