-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.js
76 lines (56 loc) · 1.54 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
67
68
69
70
71
72
73
74
75
76
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const crypto = require("crypto");
const app = express();
const randomFail = () => {
if (Math.random() <= 0.5) {
throw new Error("Random error");
}
}
let todos = [
{ id: crypto.randomUUID(), text: "Pay bills", done: true },
{ id: crypto.randomUUID(), text: "Call mom", done: false },
];
app.use(cors());
app.use(bodyParser.json());
app.get("/todo", (req, res) => {
console.log("GET /todo");
randomFail();
res.status(200).json(todos);
});
app.post("/todo", (req, res) => {
console.log("POST /todo");
randomFail();
const text = req.body.text;
const todo = { id: crypto.randomUUID(), text, done: false };
todos.unshift(todo);
res.status(201).json(todos);
});
app.delete("/todo/:id", (req, res) => {
const id = req.params.id;
console.log("DELETE /todo/" + id);
randomFail();
const index = todos.findIndex((todo) => todo.id === id);
todos.splice(index, 1);
res.status(200).json(todos);
});
app.put("/todo/:id", (req, res) => {
const id = req.params.id;
console.log("PUT /todo/" + id);
randomFail();
const text = req.body.text;
const done = req.body.done;
const index = todos.findIndex((todo) => todo.id === id);
todos[index] = { id, text, done };
res.status(200).json(todos);
});
app.put("/todo", (req, res) => {
console.log("PUT /todo");
randomFail();
todos = req.body;
res.status(200).json(todos);
});
app.listen(3000, () => {
console.log("Mock server listening on port 3000");
});