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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 323 - (hide annotations)
Mon Jul 29 17:29:32 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 2259 byte(s)
feat: add basic server and routing
1 rakin 323 import { readdir } from "fs/promises";
2     import path from "path";
3     import DiscordClient from "../client/Client";
4     import Service from "../utils/structures/Service";
5     import Controller from "./Controller";
6     import Route from "./Route";
7     import Server from "./Server";
8    
9     export interface RouterOptions {
10     routesDir: string;
11     }
12    
13     export default class Router extends Service {
14     routesDir: string;
15     controllerObjects: Array <Controller> = [];
16     routes: Route[] = [];
17    
18     constructor(client: DiscordClient, protected server: Server, { routesDir }: RouterOptions) {
19     super(client);
20     this.routesDir = routesDir;
21     }
22    
23     async loadRoutes() {
24     const files = await readdir(this.routesDir);
25    
26     for await (const file of files) {
27     if (!file.endsWith('.ts') && !file.endsWith('.js')) {
28     continue;
29     }
30    
31     console.log(`Loading routes from "${file}"...`);
32    
33     await import(path.join(this.routesDir, file));
34     }
35     }
36    
37     static insert(method: string, path: string, callback: [typeof Controller, string]) {
38     let controller = DiscordClient.client.server.router.controllerObjects.find(c => c instanceof callback[0]);
39    
40     if (!controller) {
41     controller = new callback[0]();
42     DiscordClient.client.server.router.controllerObjects.push(controller);
43     console.log("Pushed a controller");
44     }
45    
46     const route = new Route(method, path, [controller, callback[1]]);
47     DiscordClient.client.server.router.routes.push(route);
48     return route;
49     }
50    
51     static get(path: string, callback: [typeof Controller, string]) {
52     return Router.insert("GET", path, callback);
53     }
54    
55     static post(path: string, callback: [typeof Controller, string]) {
56     return Router.insert("POST", path, callback);
57     }
58    
59     static put(path: string, callback: [typeof Controller, string]) {
60     return Router.insert("PUT", path, callback);
61     }
62    
63     static patch(path: string, callback: [typeof Controller, string]) {
64     return Router.insert("PATCH", path, callback);
65     }
66    
67     static delete(path: string, callback: [typeof Controller, string]) {
68     return Router.insert("DELETE", path, callback);
69     }
70     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26