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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26