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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 53 - (show annotations)
Mon Jul 29 17:28:23 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: application/typescript
File size: 2558 byte(s)
Push api directory
1 import express, { NextFunction, Request, RequestHandler, Response, Router } from "express";
2 import { lstatSync, readdir } from "fs";
3 import path from "path";
4 import DiscordClient from "../client/Client";
5 import auth from "./Auth";
6 import apiRoute from "./routes";
7
8 const router = Router();
9
10 router.use(express.json());
11 router.use(express.urlencoded({
12 extended: false
13 }));
14 router.use(auth);
15 router.use((req: Request, res: Response, next: NextFunction) => {
16 res.setHeader('Access-Control-Allow-Origin', DiscordClient.client.config.props.global.cp_host);
17 res.setHeader('Access-Control-Allow-Methods', '*');
18 res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Allow-Methods, Content-Type, Content-Length');
19 next();
20 });
21
22 export interface Route {
23 path: string;
24 middleware: RequestHandler[];
25 get?: (req: Request, res: Response) => any,
26 post?: (req: Request, res: Response) => any,
27 put?: (req: Request, res: Response) => any,
28 patch?: (req: Request, res: Response) => any,
29 delete?: (req: Request, res: Response) => any,
30 all?: (req: Request, res: Response) => any,
31 };
32
33 export function loadRoutes(dir: string = __dirname) {
34 readdir(dir, async (err, data) => {
35 if (err) {
36 console.log(err);
37 return;
38 }
39
40 console.log(data);
41
42 for await (const file of data) {
43 if (file === '.' || file === '..')
44 continue;
45
46 let filePath = await path.resolve(dir, file);
47
48 if (lstatSync(filePath).isDirectory())
49 continue;
50
51 let route = <Route> (await import(filePath)).default;
52 let middleware = route.middleware ?? [];
53
54 if (route.get) {
55 router.get(route.path, ...middleware, route.get);
56 }
57
58 if (route.post) {
59 router.post(route.path, ...middleware, route.post);
60 }
61
62 if (route.put) {
63 router.put(route.path, ...middleware, route.put);
64 }
65
66 if (route.patch) {
67 router.patch(route.path, ...middleware, route.patch);
68 }
69
70 if (route.delete) {
71 router.delete(route.path, ...middleware, route.delete);
72 }
73
74 if (route.all) {
75 router.all(route.path, ...middleware, route.all);
76 }
77 }
78 });
79 }
80
81 loadRoutes(path.resolve(__dirname, 'routes'));
82
83 export default router;

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26