-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
94 lines (82 loc) · 2.46 KB
/
server.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
const { Pool } = require('pg');
const { authenticateJwt } = require('./auth');
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'my_database',
password: 'soccer1987',
port: 5432,
});
pool.connect((err) => {
if (err) {
console.error('Error connecting to PostgreSQL:', err);
} else {
console.log('Connected to PostgreSQL');
}
});
app.get('/api/items', authenticateJwt, (req, res) => {
pool.query('SELECT * FROM items', (err, result) => {
if (err) {
console.error('Error executing query:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.json(result.rows);
}
});
});
app.post('/api/items', authenticateJwt, (req, res) => {
const { name, description } = req.body;
pool.query(
'INSERT INTO items (name, description) VALUES ($1, $2) RETURNING *',
[name, description],
(err, result) => {
if (err) {
console.error('Error executing query:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.json(result.rows[0]);
}
}
);
});
app.put('/api/items/:id', authenticateJwt, (req, res) => {
const { id } = req.params;
const { name, description } = req.body;
pool.query(
'UPDATE items SET name = $1, description = $2 WHERE id = $3 RETURNING *',
[name, description, id],
(err, result) => {
if (err) {
console.error('Error executing query:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else if (result.rows.length === 0) {
res.status(404).json({ error: 'Item not found' });
} else {
res.json(result.rows[0]);
}
}
);
});
app.delete('/api/items/:id', authenticateJwt, (req, res) => {
const { id } = req.params;
pool.query(
'DELETE FROM items WHERE id = $1 RETURNING *',
[id],
(err, result) => {
if (err) {
console.error('Error executing query:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else if (result.rows.length === 0) {
res.status(404).json({ error: 'Item not found' });
} else {
res.json(result.rows[0]);
}
}
);
});