-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
73 lines (67 loc) · 2.14 KB
/
app.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
const express = require("express");
const app = express();
// enum
const CoffeeStatus = {
Ok: 'Correct',
NoWater: 'No water',
NoMilk: 'No milk',
NoCoffee: 'No coffee beans',
MakingCappucino: 'Making cappuccino',
MakingLatte: 'Making latte'
};
var machines = [];
var computers = [];
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function makeCoffee(index, coffeeStatus) {
const cm = machines[index];
if (cm.status == CoffeeStatus.Ok) {
cm.status = coffeeStatus;
await sleep(5000);
cm.status = CoffeeStatus.Ok;
}
}
const coffeeRouter = express.Router();
coffeeRouter.use("/create", function(req, res) {
machines.push({
name: `Кофемашина #${machines.length}`,
status: CoffeeStatus.Ok
});
res.send("Coffee created");
console.log("Coffee created");
});
// Handle GET requests like /coffee/0/status
coffeeRouter.get("/:id/:command", function(req, res) {
const command = req.params.command;
console.log(`GET request - index: ${req.params.id}; command: ${command}`);
const cm = machines[req.params.id];
if (command == "name") {
res.send(cm.name);
} else if (command == "status") {
res.send(cm.status);
}
});
// Handle POST requests like /coffee/0/make with request body: capuccino
coffeeRouter.post("/:id/:command", express.text(), function(req, res) {
const command = req.params.command;
console.log(`POST request - index: ${req.params.id}; command: ${command}; data: ${req.body}`);
if (command == "make") {
const coffeeType = req.body;
console.log(`Make ${coffeeType}`);
res.send(`Make ${coffeeType}`);
var status;
if (coffeeType == 'latte') status = CoffeeStatus.MakingLatte;
else status = CoffeeStatus.MakingCappucino;
makeCoffee(req.params.id, status);
} else if (command == "status") {
machines[req.params.id].status = req.body;
res.send("Status changed");
} else if (command == "name") {
machines[req.params.id].name = req.body;
}
});
app.use("/coffee", coffeeRouter);
app.listen(5000);