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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 325 - (hide annotations)
Mon Jul 29 17:29:32 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 1453 byte(s)
feat(api): advanced response handling
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     }
12    
13 rakin 325 async getCallbackFunction(...args: any[]) {
14 rakin 323 const [controller, method] = this.callback;
15 rakin 325 return async (req: Request, res: ExpressResponse) => {
16     let output = (controller as { [key: string]: Function })[method].call(controller, req, res, ...args);
17 rakin 324
18 rakin 325 if (output instanceof Promise) {
19     output = await output;
20 rakin 324 }
21    
22 rakin 325 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 rakin 324 };
44 rakin 323 }
45     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26