Repository navigation
Expand file tree
/
Copy pathhttp-interceptor-coronavirs.js
More file actions
73 lines (58 loc) · 1.94 KB
/
Copy pathhttp-interceptor-coronavirs.js
File metadata and controls
73 lines (58 loc) · 1.94 KB
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 fs = require('fs');
const Server = require('./lib/server');
const Router = require('./lib/middleware/router');
const param = require('./lib/aspect/param');
const app = new Server();
const router = new Router();
app.use(({req}, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.use(param);
app.use(router.get('/coronavirus/index', async ({params, route, res}, next) => {
const {getCoronavirusKeyIndex} = require('./lib/module/mock');
const index = getCoronavirusKeyIndex();
if(params.type === 'json') {
res.setHeader('Content-Type', 'application/json');
res.body = {data: index};
} else {
const handlebars = require('handlebars');
const tpl = fs.readFileSync('./view/coronavirus_index.html', {encoding: 'utf-8'});
const template = handlebars.compile(tpl);
const result = template({data: index});
res.setHeader('Content-Type', 'text/html');
res.body = result;
await next();
}
}));
app.use(router.get('/coronavirus/:date', async ({params, route, res}, next) => {
const {getCoronavirusByDate} = require('./lib/module/mock');
const data = getCoronavirusByDate(route.date);
if(params.type === 'json') {
res.setHeader('Content-Type', 'application/json');
res.body = {data};
} else {
const handlebars = require('handlebars');
const tpl = fs.readFileSync('./view/coronavirus_date.html', {encoding: 'utf-8'});
const template = handlebars.compile(tpl);
const result = template({data});
res.setHeader('Content-Type', 'text/html');
res.body = result;
}
await next();
}));
app.use(router.all('.*', async ({params, req, res}, next) => {
res.setHeader('Content-Type', 'text/html');
res.body = '<h1>Not Found</h1>';
res.statusCode = 404;
await next();
}));
// app.use(async ({req, res}, next) => {
// res.setHeader('Content-Type', 'text/html');
// res.body = '<h1>Hello world</h1>';
// await next();
// });
app.listen({
port: 9090,
host: '0.0.0.0',
});