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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 348 - (hide annotations)
Mon Jul 29 17:29:43 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 1619 byte(s)
feat: user controller
1 rakin 325 import { Request, Response as ExpressResponse } from "express";
2 rakin 348 import Controller from "./Controller";
3 rakin 325 import Response from "./Response";
4 rakin 324
5 rakin 323 export default class Route {
6 rakin 348 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 rakin 323 }
9    
10 rakin 348 middleware(...middleware: Function[]) {
11 rakin 323 this.middlewareList = [...this.middlewareList, ...middleware];
12 rakin 347 return this;
13 rakin 323 }
14    
15 rakin 325 async getCallbackFunction(...args: any[]) {
16 rakin 323 const [controller, method] = this.callback;
17 rakin 325 return async (req: Request, res: ExpressResponse) => {
18 rakin 348 let output = ((controller)[method as keyof typeof controller] as any).call(controller, req, res, ...args);
19 rakin 324
20 rakin 325 if (output instanceof Promise) {
21     output = await output;
22 rakin 324 }
23    
24 rakin 325 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 rakin 324 };
46 rakin 323 }
47     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26