-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
93 lines (83 loc) · 2.13 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
89
90
91
92
93
import { MongoClient, ObjectId } from "mongodb";
import express from "express";
const app = express();
const port = 3000;
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
app.use(express.json());
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.get("/todo/all", async (req, res) => {
try {
const todo = await client.db("todo").collection("todo").find({}).toArray();
res.send(todo);
} catch (err) {
console.log(err);
res.status(500).send("Error");
}
});
app.get("/todo/:id", async (req, res) => {
try {
const id = req.params.id;
const todo = await client
.db("todo")
.collection("todo")
.findOne({ _id: new ObjectId(id) });
res.send(todo);
} catch (err) {
console.log(err);
res.status(500).send("Error");
}
});
app.post("/todo/create", async (req, res) => {
try {
const body = req.body;
const todo = { name: body.name, status: "incomplete" };
await client.db("todo").collection("todo").insertOne(todo);
res.send("Inserted");
} catch (err) {
console.log(err);
res.status(500).send("Error");
}
});
app.post("/todo/:id/update", async (req, res) => {
try {
const body = req.body;
const id = req.params.id;
const updatedTodo = {
...(body.name && { name: body.name }),
...(body.status && { status: body.status }),
};
const result = await client
.db("todo")
.collection("todo")
.updateOne({ _id: new ObjectId(id) }, { $set: updatedTodo });
res.send(result);
} catch (err) {
console.log(err);
res.status(500).send("Error");
}
});
app.delete("/todo", async (req, res) => {
try {
const body = req.body;
await client
.db("todo")
.collection("todo")
.deleteOne({ _id: new ObjectId(body.id) });
res.send("Deleted");
} catch (err) {
console.log(err);
res.status(500).send("Error");
}
});
client
.connect()
.catch((err) => console.log(`error connecting to MongoDB\n${err}`))
.then(() => {
console.log("Connected to MongoDB");
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
});