-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
93 lines (76 loc) · 2.38 KB
/
app.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
88
89
90
91
92
93
const express = require('express');
const mongoose = require('mongoose');
const Todo = require('./models/todo');
const app = express();
require('dotenv/config');
app.use(express.json());
app.use(express.urlencoded({extended: true}));
mongoose.connect(process.env.DB_CONNECTION, ({useNewUrlParser:true, useUnifiedTopology: true})).then( ()=>{
console.log('Connected to db...');
app.listen(3000);
}).catch((err) => console.log(err));
// To send response
sendResponse = (res, statusCode, bool, msg, todo) => {
return res.status(statusCode).json({
success: bool,
message: msg,
items: todo
});
}
// Create endpoint
app.post('/api/v1/list/new', async (req, res) => {
try {
/*if(!req.body.hasOwnProperty('description')) { // validation check
return res.status(404).json({
success: false,
message: "Enter correct field name",
items: []
});
}*/
const todo = await Todo.create(req.body);
return sendResponse(res, 201, true, 'item created successfully', todo);
} catch (error) {
sendResponse(res, 500, false, 'ERROR', []);
}
});
// To read
app.get('/api/v1/list', async (req, res) => {
try {
const todo = await Todo.find().select('-__v');
return sendResponse(res, 200, true, 'Successfully fetched all the items', todo);
} catch (error) {
sendResponse(res, 500, false, 'ERROR', []);
}
});
//* To update
app.put('/api/v1/list/:id', async (req, res) => {
try {
const id = req.params.id;
let todo = await Todo.findById(id);
if(!todo) {
return sendResponse(res, 404, false, 'Todo not found', []);
}
todo = await Todo.findByIdAndUpdate(id, req.body, {
new: true,
useFindAndModify: false,
runValidators: true
});
return sendResponse(res, 202, true, 'updated successfully', todo);
} catch (error) {
sendResponse(res, 500, false, 'ERROR', []);
}
});
//* To delete
app.delete('/api/v1/list/:id', async (req, res) => {
try {
const id = req.params.id;
const todo = await Todo.findById(id);
if(!todo) {
return sendResponse(res, 404, false, 'Todo not found', []);
}
await todo.remove();
return sendResponse(res, 202, true, 'todo is deleted successfully', todo);
} catch (error) {
sendResponse(res, 500, false, 'ERROR', []);
}
});