app.ts 2.0 KB

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