app.module.ts 2.6 KB

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