/[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 347 by rakin, Mon Jul 29 17:29:42 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 7  export default class Route { Line 8  export default class Route {
8    
9      middleware(...middleware: Object[]) {      middleware(...middleware: Object[]) {
10          this.middlewareList = [...this.middlewareList, ...middleware];          this.middlewareList = [...this.middlewareList, ...middleware];
11            return this;
12      }      }
13    
14      getCallbackFunction(...args: any[]) {      async getCallbackFunction(...args: any[]) {
15          const [controller, method] = this.callback;          const [controller, method] = this.callback;
16          return (req: Request, res: Response) => {          return async (req: Request, res: ExpressResponse) => {
17              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);
18    
19              if (typeof output === 'object') {              if (output instanceof Promise) {
20                  return res.json(output);                  output = await output;
21              }              }
22    
23              return res.send(output);              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          };          };
45      }      }
46  }  }

Legend:
Removed from v.324  
changed lines
  Added in v.347

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26