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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 367 - (hide annotations)
Mon Jul 29 17:29:49 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 1960 byte(s)
feat(api): allow cors
1 rakin 323 import DiscordClient from "../client/Client";
2     import Service from "../utils/structures/Service";
3 rakin 324 import express, { Express, Router as ExpressRouter } from 'express';
4 rakin 323 import Router from "./Router";
5     import path from "path";
6 rakin 347 import rateLimit from 'express-rate-limit';
7 rakin 367 import cors from 'cors';
8 rakin 323
9     export interface ServerOptions {
10     port?: number;
11     }
12    
13     export default class Server extends Service {
14     port: number;
15     express: Express;
16     router: Router;
17    
18     constructor(client: DiscordClient, { port = 4000 }: ServerOptions = {}) {
19     super(client);
20     this.port = port;
21     this.express = express();
22     this.router = new Router(client, this, { routesDir: path.resolve(__dirname, 'routes') });
23     }
24    
25     async boot() {
26 rakin 324 type methods = 'get' | 'post' | 'put' | 'patch' | 'delete';
27     const expressRouter = ExpressRouter();
28    
29 rakin 367 expressRouter.use(cors());
30    
31 rakin 347 expressRouter.use(rateLimit({
32     windowMs: 1 * 60 * 1000,
33     max: 50,
34     standardHeaders: true,
35     legacyHeaders: true,
36     message: { code: 429, error: 'Too many requests at a time. Please try again later.' },
37     }));
38    
39 rakin 348 expressRouter.use(express.json());
40     expressRouter.use(express.urlencoded({ extended: true }));
41    
42 rakin 323 await this.router.loadRoutes();
43 rakin 324
44 rakin 348 for (const route of this.router.routes) {
45 rakin 354 // console.log(route.callback[1], route.callback[0].middleware()[route.callback[1]]);
46 rakin 348 expressRouter[route.method.toLowerCase() as methods](route.path, ...(route.callback[0].middleware()[route.callback[1]] as any[] ?? []), ...route.middlewareList as any[], await route.getCallbackFunction());
47 rakin 324 }
48    
49     this.express.use(expressRouter);
50 rakin 323 }
51    
52     async run() {
53     await this.boot();
54    
55     this.express.listen(this.port, () => {
56     console.log(`API Server listening at port ${this.port}`);
57     });
58     }
59     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26