-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
88 lines (79 loc) · 2.07 KB
/
index.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 { createServer, IncomingMessage, ServerResponse } from "node:http";
interface ServerOptions {
port?: number;
path?: string;
message?: string;
debug?: boolean;
}
class Server {
public port: number;
public customURL: string;
public customResponse: string;
public debug: boolean;
private server: ReturnType<typeof createServer>;
/**
* @param {ServerOptions} options - The options for the server
* @constructor
* @public
* @returns {void}
* @example
* new Server({ port: 8080, path: "/foo", message: "Hello, world!", debug: true });
*/
constructor(options: ServerOptions = {}) {
this.port = options.port || 8080;
this.customURL = options.path ? options.path.toString() : "/";
this.customResponse = options.message ? options.message.toString() : "200 OK!";
this.debug = options.debug || false;
this.server = createServer(this.handleRequest.bind(this));
this.listen();
}
/**
* @param {IncomingMessage} req - The request object
* @param {ServerResponse} res - The response object
* @returns {void}
* @private
*/
handleRequest(req: IncomingMessage, res: ServerResponse): void {
if (this.debug) {
console.log(`Request received: ${req.url}`);
}
if (req.url === this.customURL) {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(this.customResponse);
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
}
}
/**
* Starts the server listening on the specified port
* @returns {Promise<void>}
*/
listen(): Promise<void> {
return new Promise((resolve, reject) => {
this.server.on("error", (error) => {
reject(error);
});
this.server.listen(this.port, () => {
if (this.debug) console.log(`::debug:: [repl-uptime] => Server listening on port ${this.port}`);
resolve();
});
});
}
/**
* Stops the server
* @returns {Promise<void>}
*/
public stop(): Promise<void> {
return new Promise((resolve, reject) => {
this.server.close((error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
}
export default Server;