-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse.js
More file actions
59 lines (51 loc) · 1.35 KB
/
response.js
File metadata and controls
59 lines (51 loc) · 1.35 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
import http from 'node:http';
import fs from 'node:fs';
import hbs from 'handlebars';
class Response {
/**
* Extends the http response object with this class
* @param {http.ClientRequest} req
* @param {http.ServerResponse} res
*/
constructor(req, res) {
this.req = req;
this.res = res;
}
send(text, status = 200) {
this.res.writeHead(status, { 'Content-Type': 'text/plain' });
this.res.end(text);
}
json(data, status = 200) {
this.res.writeHead(status, { 'Content-Type': 'application/json' });
this.res.end(JSON.stringify(data));
}
notFound(text) {
this.send(text, 404);
}
redirect(location) {
this.res.writeHead(302, { Location: location });
this.res.end();
}
serverError(error, text = '500 | Internal server error') {
console.error(error);
this.render('./views/500.hbs', { title: text }, 500);
}
/**
* Response with rendered page
*
* @param {string} src Path to static template file
* @param {object} data Data for the page
*/
render(src, data, status = 200) {
try {
const file = fs.readFileSync(src);
const template = hbs.compile(file.toString());
const out = template(data);
this.res.writeHead(status, { 'Content-Type': 'text/html' });
this.res.end(out);
} catch (error) {
throw error;
}
}
}
export default Response;