-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01-middleware.js
61 lines (51 loc) · 1.32 KB
/
01-middleware.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
const express = require("express");
const app = express();
app.use(express.json());
// write a function that checks that the age of person is greater 14 or not and returns boolean
// Naive Approach
function isOldEnough(age) {
if (age > 14) return true;
else return false;
}
// using Naive approach we have to write code from 16 to 26 lines
app.get("/ride1", (req, res) => {
if (isOldEnough(req.query.age)) {
res.json({
msg: "U have successfully riden the ride1",
});
} else {
res.status(411).json({
msg: "Sorry u are not of age yet",
});
}
});
// using Naive approach we have to write code from 29 to 39 lines
app.get("/ride2", (req, res) => {
if (isOldEnough(req.query.age)) {
res.json({
msg: "U have successfully riden the ride2",
});
} else {
res.status(411).json({
msg: "Sorry u are not of age yet",
});
}
});
// Middleware - approach
function isOldEnoughMiddleware(req, res, next) {
const age = req.query.age;
if (age > 14) next();
else res.status(411).json({ msg: "Sorry u are not of age yet" });
}
app.use(isOldEnoughMiddleware);
app.get("/ride1", (req, res) => {
res.json({
msg: "U have successfully riden the ride1",
});
});
app.get("/ride2", (req, res) => {
res.json({
msg: "U have successfully riden the ride2",
});
});
app.listen(3000);