-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
84 lines (70 loc) · 1.93 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
const express = require('express');
const mongoose = require('mongoose');
const { json } = require('body-parser');
const todoModel = require('./models/todo');
mongoose.connect('mongodb://localhost:27017/todos', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log("Connected to DB"))
const app = express();
app.use(json());
app.get('/todo', async (req, res) => {
try {
const todoItemList = await todoModel.find({});
res.status(200).json(todoItemList)
} catch (error) {
res.status(500).json({
message: error
})
}
})
app.post('/todo', async (req, res) => {
const { body } = req;
const todoItem = new todoModel(body)
try {
const savedTodoItem = await todoItem.save();
res.status(200).json(savedTodoItem)
} catch (error) {
res.status(500).json({
message: error
})
}
})
app.get('/todo/:todoId', async (req, res) => {
const { params } = req;
try {
const todoItem = await todoModel.findById(params.todoId);
res.status(200).json(todoItem)
} catch (error) {
res.status(500).json({
message: error
})
}
})
app.delete('/todo/:todoId', async (req, res) => {
const { params } = req;
try {
await todoModel.findByIdAndDelete(params.todoId);
res.status(200).json({
message: `${params.todoId} is deleted.`
})
} catch (error) {
res.status(500).json({
message: error
})
}
})
app.put('/todo/:todoId', async (req, res) => {
const { params, body } = req;
try {
const updatedRecord = await todoModel.findByIdAndUpdate(params.todoId, { ...body });
res.status(200).json(updatedRecord)
} catch (error) {
res.status(500).json({
message: error
})
}
})
app.listen(5000, 'localhost', () => {
console.log('Server is listening at 5000')
})