-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
104 lines (88 loc) · 2.5 KB
/
app.js
File metadata and controls
104 lines (88 loc) · 2.5 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
97
98
99
100
101
102
103
104
const express = require('express');
const mysql = require('mysql');
const app = express();
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'chat_log',
});
app.get('/messages', async (req, res) => {
try {
const messages = await db.query('SELECT * FROM chat_log.messages');
const formattedMessages = JSON.parse(JSON.stringify(messages));
const links = [
{
rel: 'self',
href: '/messages',
},
];
res.json({
_links: links,
messages: formattedMessages,
});
}
catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.get('/messages/:id', async (req, res) => {
const id = req.params.id;
try {
const message = await db.query('SELECT * FROM chat_log.messages WHERE id = ?', [id]);
const formattedMessage = JSON.parse(JSON.stringify(message));
const links = [
{
rel: 'self',
href: `/messages/${id}`,
},
];
res.json({
_links: links,
message: formattedMessage,
});
}
catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.delete('/messages/:id', async (req, res) => {
const id = req.params.id;
try {
await db.query('DELETE FROM chat_log.messages WHERE id = ?', [id]);
res.status(204).json({ message: 'Message deleted successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/messages', async (req, res) => {
const { text } = req.body;
try {
const result = await db.query('INSERT INTO chat_log.messages (text) VALUES (?)', [text]);
const newMessageId = result.insertId;
const links = [
{
rel: 'self',
href: `/messages/${newMessageId}`,
},
];
res.status(201).json({
_links: links,
message: {
id: newMessageId,
text: text,
timestamp: new Date(),
},
});
}
catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});