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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26