-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
94 lines (78 loc) · 2.07 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
88
89
90
91
92
93
94
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
var config = require('./config');
const app = express();
app.use(express.json());
app.use(cors());
mongoose
.connect(config.db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(console.info('connected to mongoDB'))
.catch((error) => console.error(error));
const todoSchema = new mongoose.Schema({
title: String,
complete: {
type: Boolean,
default: false,
},
});
const Todo = mongoose.model('todo', todoSchema);
app.get('/todos', async (req, res) => {
try {
const todos = await Todo.find();
return res.status(200).json(todos);
} catch (error) {
console.error(`Error, get /todos ==>, ${error}`);
return res.status(500);
}
});
app.post('/todos', async (req, res) => {
try {
const newTodo = new Todo({
title: req.body.title,
});
const todo = await newTodo.save();
return res.status(201).json(todo);
} catch (error) {
console.error(`Error, post /todos ==>, ${error}`);
return res.status(500);
}
});
app.delete('/todos/:id', async (req, res) => {
try {
const { id } = req.params;
await Todo.findByIdAndDelete(id);
return res.json({
remove: true,
});
} catch (error) {
console.error(`Error, delete /todos/:id ==>, ${error}`);
return res.status(500);
}
});
app.put('/todos/:id', async (req, res) => {
try {
const { id } = req.params;
const todoUpdate = await Todo.findByIdAndUpdate(id, {
complete: req.body.complete,
});
return res.json({
update: true,
});
} catch (err) {
console.error(`Error, put /todos/:id ==>, ${error}`);
return res.status(500);
}
});
// Serve static files if in production
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});
}
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.info(`server is running on ${port}`);
});