-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.js
110 lines (77 loc) · 2.32 KB
/
tasks.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const app = require("express")();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: false
}));
// mongodb require
const mongodb = require("mongodb").MongoClient;
const ObjectID = require("mongodb").ObjectID;
// mongodb config
const DBUrl = "mongodb://127.0.0.1:27017/";
const DBName = "tasks";
// mongodb connection
let dbo = null;
mongodb.connect(DBUrl, (err, res) => {
if(err) throw err; //if have a error, throw to node server
dbo = res.db(DBName);
})
// REST API
// Endpoint tasks:
// GET tasks
app.get("/tasks", (req, res) => {
dbo.collection("tasks").find().toArray((err, body) => {
if(err) throw err;
res.json(body);
})
})
// GET one tasks with id
app.get("/tasks/:id", (req, res) => {
let id = req.params.id;
let ido = new ObjectID(id);
dbo.collection("tasks").find({
_id: ido
}).toArray((err, body) => {
if(err) throw err;
res.json(body);
})
})
// POST one tasks
app.post("/tasks", (req, res) => {
let task = req.body.task;
dbo.collection("tasks").insertOne({
task: task
}, (err, body) => {
if(err) throw err;
res.json(body);
})
})
// PUT one tasks WITH ID
app.put("/tasks/:id", (req, res) => {
let ido = new ObjectID(req.params.id);
let task = req.body.task;
dbo.collection("tasks").updateOne({
_id: ido
}, {
$set: {
task: task
}
}, (err, body) => {
if(err) throw err;
res.json(body);
})
})
// DELETE ONE TASK WITH ID
app.delete("/tasks/:id", (req, res) => {
let ido = new ObjectID(req.params.id);
dbo.collection("tasks").deleteOne({
_id: ido
}, (err, body) => {
if(err) throw err;
res.json(body);
})
})
// SERVER LISTEN PORT
app.listen(8000, (err) => {
if(err) throw err;
console.log("BERHASIL DI JALANKAN");
})