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 |
|
|
|
7 |
|
|
export interface ServerOptions { |
8 |
|
|
port?: number; |
9 |
|
|
} |
10 |
|
|
|
11 |
|
|
export default class Server extends Service { |
12 |
|
|
port: number; |
13 |
|
|
express: Express; |
14 |
|
|
router: Router; |
15 |
|
|
|
16 |
|
|
constructor(client: DiscordClient, { port = 4000 }: ServerOptions = {}) { |
17 |
|
|
super(client); |
18 |
|
|
this.port = port; |
19 |
|
|
this.express = express(); |
20 |
|
|
this.router = new Router(client, this, { routesDir: path.resolve(__dirname, 'routes') }); |
21 |
|
|
} |
22 |
|
|
|
23 |
|
|
async boot() { |
24 |
rakin |
324 |
type methods = 'get' | 'post' | 'put' | 'patch' | 'delete'; |
25 |
|
|
const expressRouter = ExpressRouter(); |
26 |
|
|
|
27 |
rakin |
323 |
await this.router.loadRoutes(); |
28 |
rakin |
324 |
|
29 |
|
|
for (const route of this.router.routes) { |
30 |
rakin |
325 |
expressRouter[route.method.toLowerCase() as methods](route.path, ...route.middlewareList, await route.getCallbackFunction()); |
31 |
rakin |
324 |
} |
32 |
|
|
|
33 |
|
|
this.express.use(expressRouter); |
34 |
rakin |
323 |
} |
35 |
|
|
|
36 |
|
|
async run() { |
37 |
|
|
await this.boot(); |
38 |
|
|
|
39 |
|
|
this.express.listen(this.port, () => { |
40 |
|
|
console.log(`API Server listening at port ${this.port}`); |
41 |
|
|
}); |
42 |
|
|
} |
43 |
|
|
} |