app.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import * as express from 'express';
  2. import { AddressInfo } from "net";
  3. import * as path from 'path';
  4. import * as bodyParser from 'body-parser';
  5. import route_index from './routes/index';
  6. import route_entity from './routes/entity';
  7. import { route_login, route_logout } from './routes/login';
  8. import LDAPFactory from './src/ldapInterface';
  9. const debug = require('debug')('my express app');
  10. const app = express();
  11. declare global {
  12. namespace Express {
  13. interface Request {
  14. ldapManager: LDAPFactory
  15. }
  16. }
  17. }
  18. // view engine setup
  19. app.set('views', path.join(__dirname, 'views'));
  20. app.set('view engine', 'pug');
  21. app.use(express.static(path.join(__dirname, 'public')));
  22. app.use(bodyParser.json());
  23. app.use(bodyParser.urlencoded({ extended: true }));
  24. app.use((req, res, next) => {
  25. req.ldapManager = new LDAPFactory();
  26. res.socket && res.socket.once('close', () => {
  27. req.ldapManager.Release();
  28. });
  29. next();
  30. });
  31. //app.use('/', route_index);
  32. app.use('/', route_index);
  33. app.use('/entity', route_entity);
  34. app.use('/login', route_login);
  35. app.use('/logout', route_logout);
  36. // catch 404 and forward to error handler
  37. app.use((req, res, next) => {
  38. const err: any = new Error('Not Found');
  39. err['status'] = 404;
  40. next(err);
  41. });
  42. // error handlers
  43. // development error handler
  44. // will print stacktrace
  45. if (app.get('env') === 'development') {
  46. app.use((err: any, req: Express.Request, res: any, next: any) => { // eslint-disable-line @typescript-eslint/no-unused-vars
  47. res.status(err[ 'status' ] || 500);
  48. res.render('error', {
  49. message: err.message,
  50. error: err
  51. });
  52. });
  53. }
  54. // production error handler
  55. // no stacktraces leaked to user
  56. app.use((err: any, req: any, res: any, next: any) => { // eslint-disable-line @typescript-eslint/no-unused-vars
  57. res.status(err.status || 500);
  58. res.render('error', {
  59. message: err.message,
  60. error: {}
  61. });
  62. });
  63. app.set('port', process.env.PORT || 3000);
  64. const server = app.listen(app.get('port'), function () {
  65. debug(`Express server listening on port ${(server.address() as AddressInfo).port}`);
  66. });