-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClient.ts
More file actions
229 lines (182 loc) · 7.21 KB
/
HttpClient.ts
File metadata and controls
229 lines (182 loc) · 7.21 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import * as http from "node:http";
import {
TIncomingMessage,
TMiddlewareHandler,
TMiddlewareNext,
TMiddlewares,
TRouteHandler,
TRoutes,
TServerResponse
} from "@Types/HttpClient";
import {getParams, Response} from "@Utils/Http";
import Logger from "@Utils/Logger";
export class HttpClient {
private _routes: TRoutes = {};
private _routesList: string[] = [];
private _globalMiddlewares: TMiddlewareHandler[] = [];
private _routeMiddlewares: TMiddlewares = {};
private readonly timeoutMs = 90000; // 1 minute 30 seconds
add(method: string, route: string, callback: TRouteHandler): void {
method = method.toUpperCase();
if (!this._routes[method]) {
this._routes[method] = {};
}
if (!this._routesList.includes(route)) {
this._routesList.push(route);
}
this._routes[method][route] = callback;
}
addRouteMiddleware(route: string, middleware: TMiddlewareHandler): void {
if (!this._routeMiddlewares[route]) {
this._routeMiddlewares[route] = [];
}
this._routeMiddlewares[route].push(middleware);
}
addGlobalMiddleware(middleware: TMiddlewareHandler): void {
this._globalMiddlewares.push(middleware);
}
listen(port: number): void {
const server = http.createServer(async (req: TIncomingMessage, res: TServerResponse) => {
res.cameInAt = Date.now();
const method = req.method?.toUpperCase() || '';
const fullUrl = req.url || '';
req.path = new URL(fullUrl, `https://${req.headers.host}`).pathname;
Logger.debug(`${method} ${fullUrl}`, 'HTTP');
if (method === 'POST' || method === 'PUT') {
try {
(req).body = await this.parseRequestBody(req);
} catch (error) {
res.statusCode = 400;
res.end('Invalid JSON');
return;
}
}
if (this._globalMiddlewares.length > 0) {
if (!(await this.handleMiddlewares(this._globalMiddlewares, req, res))) {
return;
}
}
if (this._routeMiddlewares[req.path]) {
if (!(await this.handleMiddlewares(this._routeMiddlewares[req.path], req, res))) {
return;
}
}
if (method === 'OPTIONS') {
for (const route of this._routesList) {
const routeParts = route.split('/');
const urlParts = req.path.split('/');
if (routeParts.length === urlParts.length) {
const params = getParams(req, {path: route});
if (Object.keys(params).length > 0 || route === req.path) {
return Response(res, {
status: 200,
message: 'OK'
});
}
}
}
}
if (this._routes[method] && this._routes[method][req.path]) {
return this.executeWithTimeout(this._routes[method][req.path], req, res);
}
if (this._routes[method]) {
for (const route in this._routes[method]) {
const routeParts = route.split('/').filter(Boolean);
const urlParts = req.path.split('/').filter(Boolean);
let matched = true;
const params: Record<string, string> = {};
for (let i = 0; i < routeParts.length; i++) {
const routePart = routeParts[i];
const urlPart = urlParts[i];
if (routePart === '*') {
params['wildcard'] = urlParts.slice(i).join('/');
break;
}
if (!urlPart) {
matched = false;
break;
}
if (routePart.startsWith(':')) {
params[routePart.slice(1)] = urlPart;
} else if (routePart !== urlPart) {
matched = false;
break;
}
}
if (matched) {
req.params = params;
return this.executeWithTimeout(this._routes[method][route], req, res);
}
}
}
return Response(res, {
status: 404,
message: 'Not Found'
}, 404);
});
server.listen(port, () => {
Logger.info(`Server listening on port ${port}`, 'HTTP');
});
}
private async handleMiddlewares(middlewares: TMiddlewareHandler[], req: TIncomingMessage, res: TServerResponse): Promise<boolean> {
for (const middleware of middlewares) {
const proceed = await new Promise<boolean>(resolve => middleware(req, res, resolve as TMiddlewareNext));
if (!proceed) return false;
}
return true;
}
private async executeWithTimeout(handler: TRouteHandler, req: TIncomingMessage, res: TServerResponse): Promise<void> {
let timeoutId: NodeJS.Timeout | null = null;
let isTimedOut = false;
const timeoutPromise = new Promise<void>((resolve) => {
timeoutId = setTimeout(() => {
isTimedOut = true;
if (!res.writableEnded) {
Logger.warn(`Request timeout for ${req.method} ${req.path}`, 'HTTP');
Response(res, {
status: 524,
message: 'Timeout'
}, 524);
}
resolve();
}, this.timeoutMs);
});
const handlerPromise = Promise.resolve(handler(req, res)).then(() => {
if (timeoutId && !isTimedOut) {
clearTimeout(timeoutId);
}
}).catch((error) => {
if (timeoutId && !isTimedOut) {
clearTimeout(timeoutId);
}
if (!res.writableEnded) {
Logger.error(`Request error for ${req.method} ${req.path}: ${error.message}`, 'HTTP');
console.log(error);
Response(res, {
status: 500,
message: 'Error'
}, 500);
}
});
await Promise.race([handlerPromise, timeoutPromise]);
}
private async parseRequestBody(req: TIncomingMessage): Promise<any> {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
try {
resolve(JSON.parse(body));
} catch (error) {
resolve(body);
}
});
req.on('error', reject);
});
}
}
export default function createHttpClient(): HttpClient {
return new HttpClient();
}