/[sudobot]/trunk/src/api/Route.ts
ViewVC logotype

Annotation of /trunk/src/api/Route.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 347 - (hide annotations)
Mon Jul 29 17:29:42 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 1474 byte(s)
feat(api): rate limit support
1 rakin 325 import { Request, Response as ExpressResponse } from "express";
2     import Response from "./Response";
3 rakin 324
4 rakin 323 export default class Route {
5 rakin 324 constructor(public readonly method: string, public readonly path: string, public readonly callback: [Object, string], public middlewareList: Array<any> = []) {
6 rakin 323
7     }
8    
9     middleware(...middleware: Object[]) {
10     this.middlewareList = [...this.middlewareList, ...middleware];
11 rakin 347 return this;
12 rakin 323 }
13    
14 rakin 325 async getCallbackFunction(...args: any[]) {
15 rakin 323 const [controller, method] = this.callback;
16 rakin 325 return async (req: Request, res: ExpressResponse) => {
17     let output = (controller as { [key: string]: Function })[method].call(controller, req, res, ...args);
18 rakin 324
19 rakin 325 if (output instanceof Promise) {
20     output = await output;
21 rakin 324 }
22    
23 rakin 325 if (output instanceof Response) {
24     res.status(output.status);
25    
26     for (const header in output.headers) {
27     res.setHeader(header, output.headers[header]);
28     }
29    
30     if (typeof output.body === 'object') {
31     res.json(output.body);
32     }
33     else {
34     res.send(output.body);
35     }
36     }
37     else {
38     if (typeof output === 'object') {
39     return res.json(output);
40     }
41    
42     return res.send(output);
43     }
44 rakin 324 };
45 rakin 323 }
46     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26