-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
359 lines (314 loc) · 9.71 KB
/
server.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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import http from "http";
import fs from "fs";
import path from "path";
import { parseUrl } from "./helpers/urlParser";
import { flatten2DArray } from "./helpers/flatten";
import { isRequestTypeValid } from "./helpers/request_type_validation";
import { CheckIfExistsInType } from "./helpers/TypeCheck";
import { areFilesInFolderImages } from "./helpers/getFilesInFolder";
import {
STAIC_FILE_TYPES_EXTENSIONS,
StaticFiles,
} from "./constants/StaticFileTypes";
import {
POST,
PUT,
PATCH,
DELETE,
GET,
HTTP_STATUS_NOT_FOUND,
HTTP_STATUS_OK,
HTTP_STATUS_PARTIAL_CONTENT,
HTTP_STATUS_RANGE_NOT_SATISFIABLE,
} from "./constants/responseHelpers";
import { DEFAULT_OPTIONS, Options } from "./constants/serverOpts";
import { imageTypesArray } from "./constants/StaticFileTypes";
import { InMemoryCache } from "./cache/inMemoryCache";
import {
ControllerMiddleware,
RequestType,
Routes,
RouteHandler,
RouteMiddleware,
ServerInterface,
} from "./interfaces/serverInterface";
import { ImageHandler } from "./services/imageHandler";
import mime from "mime";
import rangeParser from "range-parser";
import {
matchUrlAndMethod,
extractParamsFromUrl,
processMiddlewareChain,
handle404Page,
} from "./services/handleRequestFuncs";
type ServerType = http.Server<
typeof http.IncomingMessage,
typeof http.ServerResponse
>;
const MIDDLEWARE = "MIDDLEWARE";
export class Server implements ServerInterface {
private routes: Routes = {};
private middlewares: RouteMiddleware[] = [];
private serverName: string = "server";
private server = null as ServerType;
private options: Options = DEFAULT_OPTIONS;
private memoryCache: InMemoryCache = new InMemoryCache();
private imageHandler: ImageHandler;
constructor(options = DEFAULT_OPTIONS) {
if (options.serverName.length !== 0) {
this.serverName = options.serverName;
}
this.options = options;
this.server = http.createServer(this.handleRequesWithMiddleware.bind(this));
this.server.listen(options.port, () => {
console.log(`listening on port ${options.port}`);
});
this.imageHandler = new ImageHandler(this.memoryCache, this.options);
}
public handleRequesWithMiddleware(req: any, res: http.ServerResponse): void {
let currentMiddlewareIndex: number = 0;
if (req.url.startsWith(this.options.publicDirectory)) {
this.propagateStatic(req, res);
return;
}
const nextMiddleware = async (): Promise<void> => {
const middleware = this.middlewares[currentMiddlewareIndex];
currentMiddlewareIndex++;
if (middleware) {
middleware(req, res, nextMiddleware);
} else {
this.handleRequest(req, res);
}
};
nextMiddleware();
}
private addRoute(
method: RequestType,
path: string,
handler: RouteHandler,
middleware: ControllerMiddleware[] | null = null
): void {
if (!isRequestTypeValid(method.toLowerCase())) {
throw new Error("wrong method");
}
if (typeof handler !== "function") {
throw new Error("handler must be a func");
}
if (middleware && middleware.length > 0) {
this.routes[path] = { [method]: handler, MIDDLEWARE: middleware };
} else {
this.routes[path] = { [method]: handler };
}
}
private bodyReader(req: http.IncomingMessage): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer): void => {
chunks.push(chunk);
});
req.on("end", (): void => {
resolve(Buffer.concat(chunks).toString());
});
req.on("error", (err: Error): void => {
reject(err);
});
});
}
private async serveMultipleFilesByExtension(
req: any,
res: http.ServerResponse,
root: string
) {
const absolutePath = path.join(root, req.url);
const pathExists = fs.existsSync(absolutePath);
const areImages = await areFilesInFolderImages(absolutePath);
if (!pathExists) {
res.statusCode = 404;
res.end("File Not Found");
return;
}
if (areImages) {
console.log("Files are images");
if (this.options.compressImages) {
this.imageHandler.handleMultipleImagesCompress(
res,
req,
root,
150,
150
);
} else {
this.imageHandler.handleMultipleImages(res, req, root);
}
} else {
res.statusCode = HTTP_STATUS_OK;
res.setHeader("Content-Type", "text/plain");
res.end("The requested URL is not a file.");
}
}
private async handleNonImageStaticFile(
req: any,
res: http.ServerResponse,
path: string
) {
try {
const stat = fs.statSync(path);
const contentType = mime.getType(path) || "application/octet-stream";
res.setHeader("Content-Type", contentType);
const range = req.headers["range"];
if (range) {
const ranges = rangeParser(stat.size, range);
if (ranges && ranges.length === 1) {
const { start, end } = ranges[0];
res.statusCode = HTTP_STATUS_PARTIAL_CONTENT;
res.setHeader("Content-Range", `bytes ${start}-${end}/${stat.size}`);
res.setHeader("Content-Length", end - start + 1);
const stream = fs.createReadStream(path, { start, end });
stream.pipe(res);
return;
} else {
res.statusCode = HTTP_STATUS_RANGE_NOT_SATISFIABLE;
res.setHeader("Content-Range", `bytes */${stat.size}`);
res.end();
return;
}
}
res.setHeader("Content-Length", stat.size);
const stream = fs.createReadStream(path);
stream.pipe(res);
} catch (error) {
if (error.code === "ENOENT") {
res.statusCode = 404;
res.end("File Not Found");
} else {
res.statusCode = 500;
res.end("Internal Server Error");
console.error("Error serving static file:", error);
}
}
}
private async serveFileByExtension(
extension: StaticFiles,
req: any,
res: http.ServerResponse,
root: string
) {
const isImage = CheckIfExistsInType(extension, imageTypesArray);
const absolutePath = path.join(root, req.url);
const pathExists = fs.existsSync(absolutePath);
if (isImage && pathExists) {
if (this.options.compressImages) {
this.imageHandler.handleImageCompress(res, req, root, 200, 200);
} else {
this.imageHandler.handleImage(res, req, root);
}
}
if (!isImage) {
this.handleNonImageStaticFile(req, res, absolutePath);
}
}
private async propagateStatic(
req: any,
res: http.ServerResponse,
pathToPropagate = "public"
): Promise<void> {
const directoryName: string = pathToPropagate;
const root: string = path
.normalize(path.resolve(directoryName))
.replace(pathToPropagate, "");
const extension: string = path.extname(req.url).slice(1);
let type: string = "";
extension in STAIC_FILE_TYPES_EXTENSIONS
? (type = STAIC_FILE_TYPES_EXTENSIONS[extension as StaticFiles])
: (type = STAIC_FILE_TYPES_EXTENSIONS.html);
const supportedExtension = Boolean(type);
if (!supportedExtension) {
console.log("extension is not supported!");
res.writeHead(HTTP_STATUS_NOT_FOUND, { "Content-Type": "text/plain" });
res.end("404: File not found");
return;
}
if (!Boolean(extension)) {
console.log("no extension, check if there are static files in");
this.serveMultipleFilesByExtension(req, res, root);
} else {
this.serveFileByExtension(extension as StaticFiles, req, res, root);
}
}
private async handleRequest(req: any, res: http.ServerResponse) {
const keyRoutes: string[] = Object.keys(this.routes);
let match: boolean = false;
for (const ROUTE of keyRoutes) {
const parsedRoute: string = parseUrl(ROUTE);
const requestMethod: string = req.method.toLowerCase();
const urlMatchesMethodCorrect: boolean = matchUrlAndMethod(
req.url,
parsedRoute,
requestMethod,
this.routes,
ROUTE
);
if (urlMatchesMethodCorrect) {
const handler: RouteHandler = this.routes[ROUTE][requestMethod];
const middleware: RouteMiddleware[] = this.routes[ROUTE][MIDDLEWARE];
if (middleware) {
await processMiddlewareChain(middleware, req, res);
}
req.params = extractParamsFromUrl(req.url, parsedRoute);
req.body = await this.bodyReader(req);
await handler(req, res);
match = true;
break;
}
}
if (!match) {
return handle404Page(res);
}
res.end();
}
public get(
path: string,
handler: RouteHandler,
...middleware: ControllerMiddleware[][]
) {
this.addRoute(GET, path, handler, flatten2DArray(middleware));
}
public delete(
path: string,
handler: RouteHandler,
...middleware: ControllerMiddleware[][]
) {
this.addRoute(DELETE, path, handler, flatten2DArray(middleware));
}
public put(
path: string,
handler: RouteHandler,
...middleware: ControllerMiddleware[][]
) {
this.addRoute(PUT, path, handler, flatten2DArray(middleware));
}
public patch(
path: string,
handler: RouteHandler,
...middleware: ControllerMiddleware[][]
) {
this.addRoute(PATCH, path, handler, flatten2DArray(middleware));
}
public post(
path: string,
handler: RouteHandler,
...middleware: ControllerMiddleware[][]
) {
this.addRoute(POST, path, handler, flatten2DArray(middleware));
}
public use(middleware: RouteMiddleware): void {
this.middlewares.push(middleware);
}
public shutDown() {
console.log("shutting down...");
this.server.close(() => {
console.log(`${this.serverName} terminated.`);
process.exit(0);
});
}
}