app.module.ts 2.6 KB

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