-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (70 loc) · 2.13 KB
/
Copy pathserver.js
File metadata and controls
78 lines (70 loc) · 2.13 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
import express from 'express';
import pool from './db.js';
const app = express();
app.use(express.json());
// 전체조회
app.get('/todos', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM todos ORDER BY id');
res.json(result.rows);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// 상세조회
app.get('/todos/:id', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM todos WHERE id = $1', [req.params.id]);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Todo not found' });
}
res.json(result.rows[0]);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// 생성
app.post('/todos', async (req, res) => {
try {
const result = await pool.query(
'INSERT INTO todos (text) VALUES ($1) RETURNING *',
[req.body.text]
);
res.status(201).json(result.rows[0]);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// 수정
app.put('/todos/:id', async (req, res) => {
try {
const result = await pool.query(
`UPDATE todos
SET text = COALESCE($1, text)
WHERE id = $2
RETURNING *`,
[req.body.text ?? null, req.params.id]
);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Todo not found' });
}
res.json(result.rows[0]);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// 삭제
app.delete('/todos/:id', async (req, res) => {
try {
const result = await pool.query('DELETE FROM todos WHERE id = $1 RETURNING *', [req.params.id]);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Todo not found' });
}
res.json({ message: 'Todo deleted' });
} catch (err) {
res.status(500).json({ message: err.message });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000, http://localhost:3000');
});