app.module.ts 2.6 KB

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