-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
190 lines (166 loc) · 4.66 KB
/
app.js
File metadata and controls
190 lines (166 loc) · 4.66 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
const express = require('express');
const cors = require('cors');
const path = require('path');
const pool = require('./db');
const http = require('http');
const { WebSocketServer } = require('ws');
require('dotenv').config();
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
const port = process.env.BACKEND_PORT || 3000;
app.use(cors({
origin: "*",
methods: ["GET", "POST", "DELETE"],
allowedHeaders: ["Content-Type"]
}));
app.use(express.json());
// Used for testing local HTML files. Likely remove before publishing.
app.use(express.static(path.join(__dirname)));
//app.use(express.static(path.join(__dirname, "testSites")));
/*
broadcasts message for websocket.
*/
function broadcast(data){
const message = JSON.stringify(data);
wss.clients.forEach(client => {
if(client.readyState === client.OPEN){
client.send(message);
}
});
}
wss.on('connection', (ws) => {
console.log("WebSocket client connection.");
ws.on('close', () => console.log('WebSocket client disconnected.'))
});
/*
Base test routes.
*/
app.get('/', (req, res) => {
res.send("Hello world! My first NodeJS Express app.")
});
app.get('/status', (req, res) => {
const output = {
message: "testing",
ok: true
};
res.json(output);
});
/*
Gets all comments for the specified page_url.
*/
app.get('/comments', async (req, res) => {
try{
const { page_url } = req.query;
const result = await pool.query(
`SELECT * FROM comments WHERE page_url = $1`,
[page_url]
);
res.json(result.rows);
} catch (err) {
console.error("GET /comments:", err);
res.status(500).send("Server error");
}
});
/*
Saves comment box info to database.
*/
app.post('/comments', async (req, res) => {
try{
const {
page_url,
dom_path,
selected_text,
comment_text,
pos_x,
pos_y,
author_id
} = req.body;
const result = await pool.query(
`INSERT INTO comments
(page_url, dom_path, selected_text, comment_text, pos_x, pos_y, author_id)
VALUES ($1,$2,$3,$4,$5,$6,$7)
RETURNING *`,
[page_url, dom_path, selected_text, comment_text, pos_x, pos_y, author_id]
);
const row = result.rows[0];
broadcast({ type: 'comment_created', comment: row});
res.json(row);
} catch (err) {
console.error("POST /comments:", err);
res.status(500).send("Server error");
}
});
/*
Updates comment box info in database.
*/
app.post("/comments/:id", async (req, res) => {
try{
const {
comment_text,
pos_x,
pos_y
} = req.body;
const result = await pool.query(
`UPDATE comments
SET comment_text=$2, pos_x=$3, pos_y=$4
WHERE id=$1
RETURNING *`,
[req.params.id, comment_text, pos_x, pos_y]
);
const row = result.rows[0];
broadcast({ type: 'comment_updated', comment: row});
res.json(row);
} catch (err) {
console.error("POST /comments/:id", err);
res.status(500).send("Server error");
}
});
/*
Deletes comment box from database.
*/
app.delete("/comments/:id", async (req, res) => {
try{
const result = await pool.query(
`DELETE FROM comments WHERE id=$1
RETURNING *`,
[req.params.id]
)
if (result.rowCount === 0){
return res.status(404).send("Not found");
}
const row = result.rows[0];
broadcast({ type: "comment_deleted", comment: row });
res.send("Deleted");
} catch (err){
console.error("DELETE /comments/:id", err);
res.status(500).send("Server error");
}
});
/*
Initializes 'comments' table in database if does not already exist.
*/
async function initDB() {
await pool.query(`
CREATE TABLE IF NOT exists comments (
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
page_url TEXT NOT NULL,
dom_path TEXT,
selected_text TEXT,
comment_text TEXT NOT NULL,
pos_x INTEGER,
pos_y INTEGER,
author_id TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
}
initDB()
.then(() => {
// Starts the server
server.listen(port, () => console.log(`Server is running on port ${port}`));
})
.catch(err => {
console.error("Failed to connect to database:", err.message);
process.exit(1);
});