-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
123 lines (89 loc) · 2.65 KB
/
server.js
File metadata and controls
123 lines (89 loc) · 2.65 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
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
const PORT = process.env.PORT || 8080;
var cors = require('cors')
app.use(cors())
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const server = app.listen(PORT, () => {
console.log("Listening on port: " + PORT);
});
//Model for MongoDB
const mongoose = require('mongoose')
const Task = mongoose.Schema;
const myTask = new Task({
taskname: String,
description: String,
date: Date,
priority: Number
},
{
timestamps: true,
});
const DataSave = mongoose.model('Todo', myTask);
// end of the model
var dotenv = require('dotenv');
dotenv.config();
//Mongodb connection establishment
mongoose.connect(process.env.MONGODB_URI || 'your mongodb Uri', {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected!!!!');
});
//for production build
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
}
//handling endpoints for client request
app.get('/get', (req, res) => {
DataSave.find({})
.then((data) => {
console.log('Data: ', data);
res.json(data);
})
.catch((error) => {
console.log('error: ', error);
});
});
app.post('/save', (req, res) => {
const data = req.body;
console.log(data)
const newData = new DataSave(data);
newData.save((error) => {
if (error) {
res.status(500).json({ msg: 'Sorry, internal server errors' });
return;
}
return res.json({
msg: 'Your data has been saved!!!!!!'
});
});
})
app.delete('/delete/:id', (req, res) => {
DataSave.findByIdAndDelete(req.params.id)
.then(() => res.json('task deleted.'))
.catch(err => res.status(400).json('Error: ' + err));
});
app.get('/update/:id', (req, res) => {
DataSave.findById(req.params.id)
.then((data) => { res.json(data) })
.catch(err => console.log(err))
})
app.post('/edit', (req, res) => {
const id = req.body.id;
DataSave.find({ "_id": id })
.then(data => {
data[0].taskname = req.body.taskname;
data[0].description = req.body.description;
data[0].date = req.body.date;
data[0].priority = req.body.priority;
data[0].save()
.then(() => res.json('code updated!'))
.catch(err => res.status(400).json('Error: ' + err));
})
.catch(err => res.status(400).json('Error: ' + err));
});