-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (70 loc) · 1.77 KB
/
index.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
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(bodyParser.json());
app.use(cors());
mongoose.connect(
process.env.MONGODB_URI || "mongodb://localhost:27017/to-do-list",
{
useNewUrlParser: true
}
);
const ToDo = mongoose.model("ToDo", { title: String, done: Boolean });
app.get("/", async (req, res) => {
try {
const todos = await ToDo.find();
return res.json(todos);
} catch (error) {
console.log(error);
res.status(400).json("Couldn't find your to do list.");
}
});
app.post("/create", async (req, res) => {
try {
const toDo = new ToDo({
title: req.body.title,
done: false
});
await toDo.save();
return res.json(toDo);
} catch (error) {
console.log(error);
res.status(400).json("Error");
}
});
app.post("/update", async (req, res) => {
try {
const toDo = await ToDo.findById(req.body.id);
if (toDo === null) {
return res.status(400).json({ message: "No matching task" });
} else {
toDo.done = !toDo.done;
await toDo.save();
const toDos = await ToDo.find();
return res.json(toDos);
}
} catch (error) {
console.log(error);
res.status(400).json("Error");
}
});
app.post("/delete", async (req, res) => {
try {
const toDo = await ToDo.findById(req.body.id);
if (toDo === null) {
return res.status(400).json({ message: "No matching task" });
} else {
await toDo.remove();
const toDos = await ToDo.find();
return res.json(toDos);
}
} catch (error) {
console.log(error);
res.status(400).json("Error");
}
});
app.listen(process.env.PORT || 3001, () => {
console.log("Los geht's");
});