import bodyParser from "body-parser"; import cors from "cors"; import express, { RequestHandler } from "express"; import { PathParams } from "express-serve-static-core"; import swaggerJsdoc from "swagger-jsdoc"; import swaggerUiExpress from "swagger-ui-express"; import { Config, Logger, RedisPassport, RestResponse } from "."; export class APIServer { private serverName: string; private swaggerOptions: any; private server: express.Express; constructor(name: string, swaggerOptions: any, processListenerCount: number) { process.setMaxListeners(processListenerCount); this.serverName = name; Logger.fileName = this.serverName; this.swaggerOptions = swaggerOptions; this.server = express(); this.server.use(cors()); this.server.use( "/api-docs", swaggerUiExpress.serve, swaggerUiExpress.setup(swaggerJsdoc(this.swaggerOptions)) ); this.server.use(bodyParser.json()); this.server.use(bodyParser.urlencoded({ extended: true })); RedisPassport.initailize(this.server, Config.getInstance().session); } public addPassportStrategy(strategy: any) { RedisPassport.addStrategy(strategy); } public use(path: PathParams, ...handlers: RequestHandler[]) { this.server.use(path, handlers); } public get(path: PathParams, ...handlers: RequestHandler[]) { this.server.get(path, handlers); } public post(path: PathParams, ...handlers: RequestHandler[]) { this.server.post(path, handlers); } public run() { this.server.use((req: any, res: any, next: any) => { RestResponse.fail(res, "unsupported api request"); }); this.server.use((err: any, req: any, res: any, next: any) => { RestResponse.fail(res, err.message); }); this.server.listen(Config.getInstance().server.port, () => { Logger.getInstance().info( `Server listening on port ${Config.getInstance().server.port}` ); }); } }