-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathrequest.ts
88 lines (76 loc) · 1.68 KB
/
request.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
import net from 'net';
import fs from 'fs';
interface IHttpRequest {
/**
* Represents the type of HTTP request.
* Possible values - GET, POST, DELETE, PUT, PATCH
*
* @type {string}
*/
method: string;
/**
* The path for the HTTP request
*
* @type {string}
*/
path: string;
/**
* Headers for the HTTP request
*
* @type {Map<string, string>}
*/
headers: Map<string, string>;
/**
* Http Version for the request.
*
* @type {string}
*/
httpVersion: string;
/**
* Send the response for the request.
* Multiple overrides for this function.
*
* @param {?string} [data]
*/
send(data?: string): void;
send(data?: string, statusCode?: number): void;
/**
* Send a file to the client for the request.
* Can be used for serving HTML files
*
* @param {string} path
*/
sendFile(path: string): void;
}
class HttpRequest implements IHttpRequest {
private sock: net.Socket;
method;
path;
headers;
httpVersion;
constructor(
sock: net.Socket,
method: string,
path: string,
headers: Map<string, string> = new Map<string, string>(),
httpVersion: string
) {
this.sock = sock;
this.method = method;
this.path = path;
this.headers = headers;
this.httpVersion = httpVersion;
}
send(data = '', statusCode = 200) {
this.sock.emit('send', this, data, statusCode);
}
sendFile(path: string) {
if (fs.existsSync(path)) {
this.sock.emit('send', this, fs.readFileSync(path).toString(), 200);
return;
}
this.sock.emit('send', this, undefined, 404);
throw new Error('File does not exists: ' + path);
}
}
export { IHttpRequest, HttpRequest };