2020-06-29 02:35:05 -04:00
|
|
|
/* eslint-disable no-useless-return */
|
|
|
|
import express from 'express';
|
|
|
|
import bodyParser from 'body-parser';
|
|
|
|
import helmet from 'helmet';
|
|
|
|
import fs from 'fs-extra';
|
2020-06-29 02:50:26 -04:00
|
|
|
import { Client, Collection, Route } from '.';
|
2020-06-29 02:35:05 -04:00
|
|
|
import { Security } from '../api';
|
2020-06-29 02:50:26 -04:00
|
|
|
|
2020-06-29 02:35:05 -04:00
|
|
|
|
|
|
|
export default class Server {
|
|
|
|
public routes: Collection<Route>
|
|
|
|
|
|
|
|
public client: Client;
|
|
|
|
|
|
|
|
public security: Security;
|
|
|
|
|
|
|
|
public app: express.Express;
|
|
|
|
|
|
|
|
public options: { port: number }
|
|
|
|
|
|
|
|
constructor(client: Client, options?: { port: number }) {
|
|
|
|
this.options = options;
|
|
|
|
this.routes = new Collection();
|
|
|
|
this.client = client;
|
|
|
|
this.security = new Security(this.client);
|
|
|
|
this.app = express();
|
|
|
|
this.connect();
|
|
|
|
this.loadRoutes();
|
|
|
|
}
|
|
|
|
|
|
|
|
private async loadRoutes(): Promise<void> {
|
2020-06-29 17:20:35 -04:00
|
|
|
const routes = await fs.readdir(`${__dirname}/../api/routes`);
|
2020-06-29 02:35:05 -04:00
|
|
|
routes.forEach(async (routeFile) => {
|
|
|
|
if (routeFile === 'index.js') return;
|
|
|
|
try {
|
|
|
|
// eslint-disable-next-line new-cap
|
2020-06-29 17:19:14 -04:00
|
|
|
const route: Route = new (require(`${__dirname}/../api/routes/${routeFile}`).default)(this);
|
2020-06-29 02:35:05 -04:00
|
|
|
if (route.conf.deprecated === true) {
|
|
|
|
route.deprecated();
|
|
|
|
} else if (route.conf.maintenance === true) {
|
|
|
|
route.maintenance();
|
|
|
|
} else {
|
2020-07-04 22:57:22 -04:00
|
|
|
route.init();
|
2020-06-29 02:35:05 -04:00
|
|
|
route.bind();
|
|
|
|
}
|
|
|
|
this.routes.set(route.conf.path, route);
|
|
|
|
this.app.use(route.conf.path, route.router);
|
|
|
|
this.client.signale.success(`Successfully loaded route ${route.conf.path}`);
|
|
|
|
} catch (error) {
|
|
|
|
this.client.util.handleError(error);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private connect(): void {
|
|
|
|
this.app.set('trust proxy', 'loopback');
|
|
|
|
this.app.use(helmet({
|
|
|
|
hsts: false,
|
|
|
|
hidePoweredBy: false,
|
|
|
|
contentSecurityPolicy: {
|
|
|
|
directives: {
|
|
|
|
defaultSrc: ["'self'"],
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}));
|
|
|
|
this.app.use(bodyParser.json());
|
2020-07-23 01:22:44 -04:00
|
|
|
this.app.use(bodyParser.urlencoded({ extended: true }));
|
2020-06-29 02:35:05 -04:00
|
|
|
this.app.listen(this.options.port, () => {
|
|
|
|
this.client.signale.success(`API Server listening on port ${this.options.port}`);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|