-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
88 lines (73 loc) · 1.92 KB
/
server.js
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
const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
app.use(express.json());
const port = 3000;
// Connection to Mongodb
mongoose.connect("mongodb+srv://najimabdessamaddev:C9p?dT.@7X*5*[email protected]/?retryWrites=true&w=majority", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('Connected to the database');
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
})
.catch((error) => {
console.error('Error connecting to the database', error);
});
// User model
const User = require('./models/User');
// GET
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal server error' });
}
});
// POST
app.post('/users', async (req, res) => {
try {
const newUser = new User(req.body);
await newUser.save();
res.status(201).json(newUser);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal server error' });
}
});
// PUT
app.put('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const updatedUser = await User.findByIdAndUpdate(id, req.body, {
new: true,
});
if (!updatedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json(updatedUser);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal server error' });
}
});
// DELETE
app.delete('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const deletedUser = await User.findByIdAndDelete(id);
if (!deletedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json(deletedUser);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal server error' });
}
});