/[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 324 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 } from "express";  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<any> = []) {      constructor(public readonly method: string, public readonly path: string, public readonly callback: [Object, string], public middlewareList: Array<any> = []) {
# Line 9  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 (req: Request, res: Response) => {          return async (req: Request, res: ExpressResponse) => {
16              const output = (controller as { [key: string]: Function })[method].call(controller, req, res, ...args);              let output = (controller as { [key: string]: Function })[method].call(controller, req, res, ...args);
17    
18              if (typeof output === 'object') {              if (output instanceof Promise) {
19                  return res.json(output);                  output = await output;
20              }              }
21    
22              return res.send(output);              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.324  
changed lines
  Added in v.325

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26