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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 367 - (show 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 import DiscordClient from "../client/Client";
2 import Service from "../utils/structures/Service";
3 import express, { Express, Router as ExpressRouter } from 'express';
4 import Router from "./Router";
5 import path from "path";
6 import rateLimit from 'express-rate-limit';
7 import cors from 'cors';
8
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 type methods = 'get' | 'post' | 'put' | 'patch' | 'delete';
27 const expressRouter = ExpressRouter();
28
29 expressRouter.use(cors());
30
31 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 expressRouter.use(express.json());
40 expressRouter.use(express.urlencoded({ extended: true }));
41
42 await this.router.loadRoutes();
43
44 for (const route of this.router.routes) {
45 // console.log(route.callback[1], route.callback[0].middleware()[route.callback[1]]);
46 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 }
48
49 this.express.use(expressRouter);
50 }
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