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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 323 by rakin, Mon Jul 29 17:29:32 2024 UTC revision 348 by rakin, Mon Jul 29 17:29:43 2024 UTC
# Line 1  Line 1 
1  export default class Route {  import { Request, Response as ExpressResponse } from "express";
2      constructor(public readonly method: string, public readonly path: string, public readonly callback: [Object, string], public middlewareList: Array<Object> = []) {  import Controller from "./Controller";
3    import Response from "./Response";
4    
5    export default class Route {
6        constructor(public readonly method: string, public readonly path: string, public readonly callback: [Controller, string], public middlewareList: Array<Function> = []) {
7            this.middlewareList = [...this.middlewareList, ...callback[0].globalMiddleware()];
8      }      }
9    
10      middleware(...middleware: Object[]) {      middleware(...middleware: Function[]) {
11          this.middlewareList = [...this.middlewareList, ...middleware];          this.middlewareList = [...this.middlewareList, ...middleware];
12            return this;
13      }      }
14    
15      getCallbackFunction(...args: any[]) {      async getCallbackFunction(...args: any[]) {
16          const [controller, method] = this.callback;          const [controller, method] = this.callback;
17          return () => (controller as { [key: string]: Function })[method].call(controller, ...args);          return async (req: Request, res: ExpressResponse) => {
18                let output = ((controller)[method as keyof typeof controller] as any).call(controller, req, res, ...args);
19    
20                if (output instanceof Promise) {
21                    output = await output;
22                }
23    
24                if (output instanceof Response) {
25                    res.status(output.status);
26    
27                    for (const header in output.headers) {
28                        res.setHeader(header, output.headers[header]);
29                    }
30    
31                    if (typeof output.body === 'object') {
32                        res.json(output.body);
33                    }
34                    else {
35                        res.send(output.body);
36                    }
37                }
38                else {
39                    if (typeof output === 'object') {
40                        return res.json(output);
41                    }
42        
43                    return res.send(output);
44                }
45            };
46      }      }
47  }  }

Legend:
Removed from v.323  
changed lines
  Added in v.348

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26