app.module.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
  2. import cookieSession = require('cookie-session');
  3. import { RequestHandler } from 'express';
  4. import { GraphQLDateTime } from 'graphql-iso-date';
  5. import * as ms from 'ms';
  6. import { ApiModule } from './api/api.module';
  7. import { ConfigModule } from './config/config.module';
  8. import { ConfigService } from './config/config.service';
  9. import { validateCustomFieldsConfig } from './entity/custom-entity-fields';
  10. import { I18nModule } from './i18n/i18n.module';
  11. import { I18nService } from './i18n/i18n.service';
  12. @Module({
  13. imports: [ConfigModule, I18nModule, ApiModule],
  14. })
  15. export class AppModule implements NestModule {
  16. constructor(private configService: ConfigService, private i18nService: I18nService) {}
  17. configure(consumer: MiddlewareConsumer) {
  18. validateCustomFieldsConfig(this.configService.customFields);
  19. const defaultMiddleware: Array<{ handler: RequestHandler; route?: string }> = [
  20. { handler: this.i18nService.handle(), route: this.configService.apiPath },
  21. ];
  22. if (this.configService.authOptions.tokenMethod === 'cookie') {
  23. defaultMiddleware.push({
  24. handler: cookieSession({
  25. name: 'session',
  26. secret: this.configService.authOptions.sessionSecret,
  27. httpOnly: true,
  28. }),
  29. route: this.configService.apiPath,
  30. });
  31. }
  32. const allMiddleware = defaultMiddleware.concat(this.configService.middleware);
  33. const middlewareByRoute = this.groupMiddlewareByRoute(allMiddleware);
  34. for (const [route, handlers] of Object.entries(middlewareByRoute)) {
  35. consumer.apply(...handlers).forRoutes(route);
  36. }
  37. }
  38. /**
  39. * Groups middleware handlers together in an object with the route as the key.
  40. */
  41. private groupMiddlewareByRoute(
  42. middlewareArray: Array<{ handler: RequestHandler; route?: string }>,
  43. ): { [route: string]: RequestHandler[] } {
  44. const result = {} as { [route: string]: RequestHandler[] };
  45. for (const middleware of middlewareArray) {
  46. const route = middleware.route || this.configService.apiPath;
  47. if (!result[route]) {
  48. result[route] = [];
  49. }
  50. result[route].push(middleware.handler);
  51. }
  52. return result;
  53. }
  54. }