1
0

app.module.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { MiddlewareConsumer, Module, NestModule, OnApplicationShutdown } from '@nestjs/common';
  2. import cookieSession = require('cookie-session');
  3. import { RequestHandler } from 'express';
  4. import { ApiModule } from './api/api.module';
  5. import { ConfigModule } from './config/config.module';
  6. import { ConfigService } from './config/config.service';
  7. import { Logger } from './config/logger/vendure-logger';
  8. import { I18nModule } from './i18n/i18n.module';
  9. import { I18nService } from './i18n/i18n.service';
  10. import { PluginModule } from './plugin/plugin.module';
  11. @Module({
  12. imports: [ConfigModule, I18nModule, ApiModule, PluginModule.forRoot()],
  13. })
  14. export class AppModule implements NestModule, OnApplicationShutdown {
  15. constructor(private configService: ConfigService, private i18nService: I18nService) {}
  16. configure(consumer: MiddlewareConsumer) {
  17. const { adminApiPath, shopApiPath } = this.configService;
  18. const i18nextHandler = this.i18nService.handle();
  19. const defaultMiddleware: Array<{ handler: RequestHandler; route?: string }> = [
  20. { handler: i18nextHandler, route: adminApiPath },
  21. { handler: i18nextHandler, route: shopApiPath },
  22. ];
  23. if (this.configService.authOptions.tokenMethod === 'cookie') {
  24. const cookieHandler = cookieSession({
  25. name: 'session',
  26. secret: this.configService.authOptions.sessionSecret,
  27. httpOnly: true,
  28. });
  29. defaultMiddleware.push({ handler: cookieHandler, route: adminApiPath });
  30. defaultMiddleware.push({ handler: cookieHandler, route: shopApiPath });
  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. onApplicationShutdown(signal?: string) {
  39. if (signal) {
  40. Logger.info('Received shutdown signal:' + signal);
  41. }
  42. }
  43. /**
  44. * Groups middleware handlers together in an object with the route as the key.
  45. */
  46. private groupMiddlewareByRoute(
  47. middlewareArray: Array<{ handler: RequestHandler; route?: string }>,
  48. ): { [route: string]: RequestHandler[] } {
  49. const result = {} as { [route: string]: RequestHandler[] };
  50. for (const middleware of middlewareArray) {
  51. const route = middleware.route || this.configService.adminApiPath;
  52. if (!result[route]) {
  53. result[route] = [];
  54. }
  55. result[route].push(middleware.handler);
  56. }
  57. return result;
  58. }
  59. }