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
| import * as http from 'http';
class Context { request: http.IncomingMessage; response: http.ServerResponse; query: any; body: any; url: string; method: string; isEnd: boolean = false; nextInx: number = -1; statusCode:number = 200; middleware:Handler[] = []; errorHandler: (err: Error, ctx: Context) => Promise<void>; responseHeader: Map<String, string> = new Map<String, string>(); constructor(req: http.IncomingMessage, res: http.ServerResponse) { this.request = req; this.response = res; this.url = req.url ?? ""; this.method = req.method?.toLocaleUpperCase() ?? "GET"; this.errorHandler = async (err, ctx) => {}; } timeout(time: number){ if (time <= 0) return; setTimeout(() => { this.statusCode = 500; this.send("server timeout"); }, time); } next(info?: any) { if (info) { this.nextInx = this.middleware.length -1; this.errorHandler(info, this); return; } this.nextInx += 1; if (this.nextInx >= this.middleware.length || this.isEnd) return; try { this.middleware[this.nextInx](this); } catch (err) { this.nextInx = this.middleware.length -1; this.errorHandler(err, this); } } send(str: string) { if (this.isEnd) return; this.response.setHeader('Content-Type', 'text/plain; charset=utf-8'); for(let key in this.responseHeader.keys()) { this.response.setHeader(key, this.responseHeader.get(key) ?? ''); } this.response.statusCode = this.statusCode || 200; this.response.write(str); this.response.end(); this.isEnd = true; }
json(str: Object) { if (this.isEnd) return; this.response.setHeader('Content-Type', 'application/json; charset=utf-8'); for(let key in this.responseHeader.keys()) { this.response.setHeader(key, this.responseHeader.get(key) ?? ''); } this.response.statusCode = this.statusCode || 200; this.response.write(str); this.response.end(); this.isEnd = true; }
setHeader(key: string, value: string) { this.responseHeader.set(key, value); } }
|