-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
92 lines (79 loc) · 2.3 KB
/
app.js
File metadata and controls
92 lines (79 loc) · 2.3 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
const express = require('express');
const app = express();
const path = require('path');
const userModel = require('./models/user');
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// View engine
app.set('view engine', 'ejs');
// Static files
app.use(express.static(path.join(__dirname, 'public')));
// Routes
app.get('/', (req, res) => {
res.render('index');
});
app.get('/read', async (req, res) => {
try {
let users = await userModel.find();
res.render('read', { users });
} catch (err) {
console.error(err);
res.status(500).send('Error reading users');
}
});
app.post('/create', async (req, res) => {
try {
let { name, email, image } = req.body;
// Validation
if (!name || !email || !image) {
return res.status(400).send('All fields are required');
}
await userModel.create({ name, email, image });
res.redirect('/read');
} catch (err) {
console.error(err);
res.status(500).send('Error creating user');
}
});
app.get('/delete/:id', async (req, res) => {
try {
await userModel.findByIdAndDelete(req.params.id);
res.redirect('/read'); // Always redirect so /read shows full array
} catch (err) {
console.error(err);
res.status(500).send('Error deleting user');
}
});
app.get('/edit/:id', async (req, res) => {
try {
let user = await userModel.findById(req.params.id);
if (!user) return res.status(404).send('User not found');
res.render('edit', { user });
} catch (err) {
console.error(err);
res.status(500).send('Error loading user for edit');
}
});
app.post('/edit/:id', async (req, res) => {
try {
let { name, email, image } = req.body;
// Validation
if (!name || !email || !image) {
return res.status(400).send('All fields are required');
}
await userModel.findByIdAndUpdate(req.params.id, {
name,
email,
image
});
res.redirect('/read');
} catch (err) {
console.error(err);
res.status(500).send('Error updating user');
}
});
// Start server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});