-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
100 lines (68 loc) · 1.98 KB
/
server.ts
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
declare const require;
var express = require('express');
var bodyParser = require('body-parser');
var _ = require('lodash');
import {lessonsData} from './lessons';
var app = express();
app.use(express.static('.'));
app.use(bodyParser.json());
app.use(bodyParser.text());
const lessons = lessonsData;
app.route('/lessons')
.get((req, res) => {
var filtered = lessons;
if (req.query.search) {
console.log(req.query.search);
filtered = filtered.filter(
lesson => lesson.description.indexOf(req.query.search) != - 1);
}
res.status(200).json(filtered);
})
.post((req, res) => {
lessons.push(req.body);
res.status(200).send();
});
app.route('/lessons/:lessonId')
.delete((req,res) => {
const lessonId = req.params.lessonId;
console.log("deleting lesson ", lessonId);
const index = _.find(lessons,
lesson => lesson.id === lessonId
);
lessons.splice(index, 1);
res.status(200).send();
})
.get((req, res)=>{
let filtered = lessons.filter(lesson => lesson.id == req.params.lessonId);
console.log('the filtered array is:' + filtered);
res.status(200).json(filtered);
});
app.route('/flakylessons')
.get((req, res) => {
const num = Math.round(Math.random() * 10);
if (num % 2 == 0) {
res.status(200).json(lessons);
}
else {
res.status(500).send();
}
});
app.route('/delayedlessons')
.get((req, res) => {
setTimeout(() => {
var filtered = lessons;
if (req.query.search) {
console.log(req.query.search);
filtered = filtered.filter(
lesson => lesson.description.indexOf(req.query.search) != - 1);
}
res.status(200).json(filtered);
}, 1000);
});
function redirectRouterLessonUnmatched(req,res) {
res.sendFile("index.html", { root: './' });
}
app.use(redirectRouterLessonUnmatched);
var server = app.listen(8080, function() {
console.log("Server running at http://localhost:" + server.address().port);
});