app.module.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { MiddlewareConsumer, Module, NestModule, OnApplicationShutdown } from '@nestjs/common';
  2. import { RequestHandler } from 'express';
  3. import { ApiModule } from './api/api.module';
  4. import { ConfigModule } from './config/config.module';
  5. import { ConfigService } from './config/config.service';
  6. import { Logger } from './config/logger/vendure-logger';
  7. import { HealthCheckModule } from './health-check/health-check.module';
  8. import { I18nModule } from './i18n/i18n.module';
  9. import { I18nService } from './i18n/i18n.service';
  10. import { PluginModule } from './plugin/plugin.module';
  11. import { ProcessContextModule } from './process-context/process-context.module';
  12. @Module({
  13. imports: [
  14. ConfigModule,
  15. I18nModule,
  16. ApiModule,
  17. PluginModule.forRoot(),
  18. ProcessContextModule.forRoot(),
  19. HealthCheckModule,
  20. ],
  21. })
  22. export class AppModule implements NestModule, OnApplicationShutdown {
  23. constructor(private configService: ConfigService, private i18nService: I18nService) {}
  24. configure(consumer: MiddlewareConsumer) {
  25. const { adminApiPath, shopApiPath, middleware } = this.configService.apiOptions;
  26. const i18nextHandler = this.i18nService.handle();
  27. const defaultMiddleware: Array<{ handler: RequestHandler; route?: string }> = [
  28. { handler: i18nextHandler, route: adminApiPath },
  29. { handler: i18nextHandler, route: shopApiPath },
  30. ];
  31. const allMiddleware = defaultMiddleware.concat(middleware);
  32. const middlewareByRoute = this.groupMiddlewareByRoute(allMiddleware);
  33. for (const [route, handlers] of Object.entries(middlewareByRoute)) {
  34. consumer.apply(...handlers).forRoutes(route);
  35. }
  36. }
  37. async onApplicationShutdown(signal?: string) {
  38. if (signal) {
  39. Logger.info('Received shutdown signal:' + signal);
  40. }
  41. }
  42. /**
  43. * Groups middleware handlers together in an object with the route as the key.
  44. */
  45. private groupMiddlewareByRoute(
  46. middlewareArray: Array<{ handler: RequestHandler; route?: string }>,
  47. ): { [route: string]: RequestHandler[] } {
  48. const result = {} as { [route: string]: RequestHandler[] };
  49. for (const middleware of middlewareArray) {
  50. const route = middleware.route || this.configService.apiOptions.adminApiPath;
  51. if (!result[route]) {
  52. result[route] = [];
  53. }
  54. result[route].push(middleware.handler);
  55. }
  56. return result;
  57. }
  58. }