-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
66 lines (45 loc) · 1.24 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
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv").config();
const app = express();
app.use(express.json());
app.use(cors());
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("Connected to MongoDB"))
.catch(console.error);
// Models
const Todo = require("./models/Todo");
app.get("/todos", async (req, res) => {
const todos = await Todo.find();
res.json(todos);
});
app.post("/todo/new", (req, res) => {
const todo = new Todo({
text: req.body.text,
});
todo.save();
res.json(todo);
});
app.delete("/todo/delete/:id", async (req, res) => {
const result = await Todo.findByIdAndDelete(req.params.id);
res.json({ result });
});
app.get("/todo/complete/:id", async (req, res) => {
const todo = await Todo.findById(req.params.id);
todo.complete = !todo.complete;
todo.save();
res.json(todo);
});
app.put("/todo/update/:id", async (req, res) => {
const todo = await Todo.findById(req.params.id);
todo.text = req.body.text;
todo.save();
res.json(todo);
});
PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));