-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
105 lines (92 loc) · 2.23 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
94
95
96
97
98
99
100
101
102
103
104
105
let express = require("express");
let path = require("path");
let methodOverride = require("method-override");
let app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride("_method"));
app.use(
methodOverride(function(req, res) {
if (req.body && typeof req.body === "object" && "_method" in req.body) {
// look in urlencoded POST bodies and delete it
var method = req.body._method;
delete req.body._method;
return method;
}
})
);
app.use(express.static(path.join(__dirname, "public")));
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
let todos = [
{
id: Math.floor(Math.random() * 100),
title: "Pick up milk",
completed: false,
},
{
id: Math.floor(Math.random() * 100),
title: "Learn templating",
completed: false,
},
{
id: Math.floor(Math.random() * 100),
title: "Learn loops",
completed: false,
},
{
id: Math.floor(Math.random() * 100),
title: "Learn about extending layouts",
completed: false,
},
{
id: Math.floor(Math.random() * 100),
title: "Refactor route handlers to controller",
completed: false,
},
{
id: Math.floor(Math.random() * 100),
title: "Refactor route handlers to a controller",
completed: false,
},
{
id: Math.floor(Math.random() * 100),
title: "Use Twitter Bootstrap to make things look a little better",
completed: false,
},
];
app.get("/todos", function(req, res) {
res.render("todos", {
todos: todos,
});
});
app.post("/todos", function(req, res) {
let todo = {
id: Math.floor(Math.random() * 100),
title: req.body.title,
completed: false,
};
todos.push(todo);
res.redirect("/todos");
});
app.put("/todos/:id", function(req, res) {
let id = req.params.id;
todos.forEach(function(todo) {
if (todo.id == id) {
todo.completed = req.body.hasOwnProperty("todo");
}
});
return res.redirect("/todos");
});
app.delete("/todos/:id", function(req, res) {
let id = req.params.id;
todos = todos.filter(function (todo) {
if (todo.id == req.params.id) {
return false;
} else {
return true;
}
});
res.redirect("/todos");
});
app.listen(3000);