-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
240 lines (182 loc) · 5.75 KB
/
app.js
File metadata and controls
240 lines (182 loc) · 5.75 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// import expres
const express = require('express');
//import body-parser to handle data
const bodyParser = require('body-parser');
//import axios for making HTTP requests
const axios = require('axios');
// create an express application
const app = express();
//define the port
const PORT = 3000;
// test the database connection
const pool = require('./db');
pool.query('SELECT NOW()', (err, res) => {
if (err) {
console.error('Connection error:', err);
} else {
console.log('Connected to PostgreSQL at:', res.rows[0].now);
}
});
const session = require('express-session');
app.use(session({
secret: '67naucs67',
resave: false,
saveUninitialized: false
}));
// configure express to use ejs as the view engine and serve static files
app.set('view engine', 'ejs');
app.use(express.static('public'));
// parse url-encoded form data from POST requests
app.use(bodyParser.urlencoded({ extended: true }));
// a temporary array stoing posts in memory
let posts = [];
// home route: display all posts with optional filtering
app.get('/', async (req, res) => {
const user_id = req.session.user_id;
if (!user_id) {
return res.redirect('/signup');
}
const filter = req.query.filter;
let posts;
try {
if (filter) {
const result = await pool.query(
'SELECT * FROM blogs WHERE category = $1 ORDER BY date_created DESC',
[filter]
);
posts = result.rows;
} else {
const result = await pool.query(
'SELECT * FROM blogs ORDER BY date_created DESC'
);
posts = result.rows;
}
res.render('index', { posts });
} catch (err) {
console.error('Error fetching posts:', err.message);
res.status(500).send('Failed to load posts.');
}
});
// route to create new posts
app.post('/create', async (req, res) => {
const { title, content, category } = req.body;
const creator_user_id = req.session.user_id;
const creator_name = req.session.name;
if (!creator_user_id) {
return res.send('You must be signed in to create a post.');
}
let joke = '';
try {
const response = await axios.get('https://v2.jokeapi.dev/joke/Any?type=single');
joke = response.data.joke || 'No joke found.';
} catch (error) {
console.error('JokeAPI error:', error.message);
joke = 'Could not fetch a joke.';
}
try {
await pool.query(
`INSERT INTO blogs (creator_name, creator_user_id, title, body, category, date_created, joke)
VALUES ($1, $2, $3, $4, $5, CURRENT_TIMESTAMP, $6)`,
[creator_name, creator_user_id, title, content, category, joke]
);
res.redirect('/');
} catch (err) {
console.error('Database insert error:', err.message);
res.status(500).send('Failed to create post.');
}
});
// Route to load edit form for a post
app.get('/edit/:id', async (req, res) => {
const blog_id = req.params.id;
const user_id = req.session.user_id;
const result = await pool.query(
'SELECT * FROM blogs WHERE blog_id = $1 AND creator_user_id = $2',
[blog_id, user_id]
);
if (result.rows.length === 0) {
return res.status(403).send('You can only edit your own posts.');
}
res.render('edit', { post: result.rows[0] });
});
// route to handle sumbison
app.post('/edit/:id', async (req, res) => {
const blog_id = req.params.id;
const user_id = req.session.user_id;
const { title, content, category } = req.body;
if (!user_id) {
return res.status(403).send('You must be signed in to edit posts.');
}
try {
// Update only if the logged-in user is the creator
const result = await pool.query(
`UPDATE blogs
SET title = $1, body = $2, category = $3, date_created = CURRENT_TIMESTAMP
WHERE blog_id = $4 AND creator_user_id = $5`,
[title, content, category, blog_id, user_id]
);
if (result.rowCount === 0) {
return res.status(403).send('You can only edit your own posts.');
}
res.redirect('/');
} catch (err) {
console.error('Edit error:', err.message);
res.status(500).send('Failed to update post.');
}
});
// route to delete a post using the id
app.get('/delete/:id', async (req, res) => {
const blog_id = req.params.id;
const user_id = req.session.user_id;
try {
await pool.query(
'DELETE FROM blogs WHERE blog_id = $1 AND creator_user_id = $2',
[blog_id, user_id]
);
res.redirect('/');
} catch (err) {
console.error('Delete error:', err.message);
res.status(500).send('Failed to delete post.');
}
});
// sign up route
app.get('/signup', (req, res) => {
res.render('signup');
});
app.post('/signup', async (req, res) => {
const { user_id, name, password } = req.body;
try {
const existing = await pool.query(
'SELECT * FROM users WHERE user_id = $1',
[user_id]
);
if (existing.rows.length > 0) {
return res.send('User ID already taken. Try another.');
}
await pool.query(
'INSERT INTO users (user_id, name, password) VALUES ($1, $2, $3)',
[user_id, name, password]
);
return res.redirect('/signin');
} catch (err) {
console.error('Signup error:', err.message);
return res.status(500).send('Signup failed due to a server error.');
}
});
// sign in route
app.get('/signin', (req, res) => {
res.render('signin');
});
app.post('/signin', async (req, res) => {
const { user_id, password } = req.body;
const result = await pool.query('SELECT * FROM users WHERE user_id = $1 AND password = $2', [user_id, password]);
if (result.rows.length === 0) {
return res.send('Invalid credentials. Try again.');
}
req.session.user_id = result.rows[0].user_id;
req.session.name = result.rows[0].name;
res.redirect('/');
});
// starting the express server on defined porrt = 3000
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});