Skip to content

Instantly share code, notes, and snippets.

@GautamPanickar
Last active September 5, 2022 05:40
Show Gist options
  • Save GautamPanickar/3e0a08ba878478f545da590056c232ce to your computer and use it in GitHub Desktop.
Save GautamPanickar/3e0a08ba878478f545da590056c232ce to your computer and use it in GitHub Desktop.
import * as BodyParser from 'body-parser';
import * as Express from 'express';
import UserController from './controllers/user-controller';
import ErrorMiddleware from './middlewares/base/errormiddleware';
import Controller from './types/controller';
class App {
public app: Express.Application;
public constructor(controllers: Controller[]) {
this.app = Express();
this.initializeBaseConfig();
this.initializeControllers(controllers);
this.initializeMiddleWares();
}
/**
* Application config
*/
private initializeBaseConfig(): void {
// Allow any method from any host and log requests
this.app.use((req: Express.Request, res: Express.Response, next: Express.NextFunction) => {
const corsWhitelist = [
'abc.com',
'def.com',
'localhost:4200',
'abc.in'
];
for (let i = 0; i < corsWhitelist.length; i++) {
if (req.headers.origin.indexOf(corsWhitelist[i]) >= 0) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
break;
}
}
// res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, DELETE, PATCH');
if ('OPTIONS' === req.method) {
res.sendStatus(200);
} else {
console.log(`${req.ip} ${req.method} ${req.url}`);
next();
}
});
// support application/json type post data
this.app.use(BodyParser.json());
// support application/x-www-form-urlencoded post data
this.app.use(BodyParser.urlencoded({ extended: false }));
}
/**
* Initializes different middlewares.
*/
private initializeMiddleWares() {
this.app.use(ErrorMiddleware);
}
/**
* Initializes the controllers.
* @param controllers
*/
public initializeControllers(controllers: Controller[]): void {
controllers.forEach((controller: Controller) => {
this.app.use('/', controller.router);
});
}
}
export default new App([
new UserController()
]).app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment