-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
72 lines (68 loc) · 2.41 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
const fs = require('fs');
const Response = require('./lib/response');
const CONTENT_TYPES = require('./lib/mimeTypes');
const { loadTemplate } = require('./lib/viewTemplate');
const STATIC_FOLDER = `${__dirname}/public`;
let visitorCount = 0;
const serveStaticFile = (req) => {
const path = `${STATIC_FOLDER}${req.url}`;
const stat = fs.existsSync(path) && fs.statSync(path);
if (!stat || !stat.isFile()) return new Response();
const [, extension] = path.match(/.*\.(.*)$/) || [];
const contentType = CONTENT_TYPES[extension];
const content = fs.readFileSync(path);
const res = new Response();
res.setHeader('Content-Type', contentType);
res.setHeader('Content-Length', content.length);
res.statusCode = 200;
res.body = content;
return res;
}
const serveHomePage = (req) => {
visitorCount++;
const html = loadTemplate('home.html', { visitorCount });
const res = new Response();
if (!req.headers['Cookie']) res.setHeader('Set-Cookie', `sessionId=${new Date().getTime()}`);
res.setHeader('Content-Type', CONTENT_TYPES.html);
res.setHeader('Content-Length', html.length);
res.statusCode = 200;
res.body = html;
return res;
}
const generateStudentResponse = (student) => {
const html = loadTemplate('student.html', student);
const res = new Response();
res.setHeader('Content-Type', CONTENT_TYPES.html);
res.setHeader('Content-Length', html.length);
res.statusCode = 200;
res.body = html;
return res;
}
const registerStudent = (req) => {
return generateStudentResponse(req.query);
}
const registerStudentPost = (req) => {
return generateStudentResponse(req.body);
}
const serveVisitorCount = (req) => {
const text = `${visitorCount}`;
const res = new Response();
res.setHeader('Content-Type', CONTENT_TYPES.txt);
res.setHeader('Content-Length', text.length);
res.statusCode = 200;
res.body = text;
return res;
}
const findHandler = (req) => {
if (req.method === 'GET' && req.url === '/') return serveHomePage;
if (req.method === 'GET' && req.url === '/visitorCount') return serveVisitorCount;
if (req.method === 'GET' && req.url === '/registerStudent') return registerStudent;
if (req.method === 'POST' && req.url === '/registerStudent') return registerStudentPost;
if (req.method === 'GET') return serveStaticFile;
return () => new Response();
}
const processRequest = (req) => {
const handler = findHandler(req);
return handler(req);
}
module.exports = { processRequest };