app.module.ts 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { MiddlewareConsumer, Module, NestModule, OnModuleDestroy } from '@nestjs/common';
  2. import cookieSession = require('cookie-session');
  3. import { RequestHandler } from 'express';
  4. import { GraphQLDateTime } from 'graphql-iso-date';
  5. import { ApiModule } from './api/api.module';
  6. import { ConfigModule } from './config/config.module';
  7. import { ConfigService } from './config/config.service';
  8. import { validateCustomFieldsConfig } from './entity/custom-entity-fields';
  9. import { I18nModule } from './i18n/i18n.module';
  10. import { I18nService } from './i18n/i18n.service';
  11. @Module({
  12. imports: [ConfigModule, I18nModule, ApiModule],
  13. })
  14. export class AppModule implements NestModule, OnModuleDestroy {
  15. constructor(private configService: ConfigService, private i18nService: I18nService) {}
  16. configure(consumer: MiddlewareConsumer) {
  17. const { adminApiPath, shopApiPath } = this.configService;
  18. // tslint:disable-next-line:no-floating-promises
  19. validateCustomFieldsConfig(this.configService.customFields);
  20. const i18nextHandler = this.i18nService.handle();
  21. const defaultMiddleware: Array<{ handler: RequestHandler; route?: string }> = [
  22. { handler: i18nextHandler, route: adminApiPath },
  23. { handler: i18nextHandler, route: shopApiPath },
  24. ];
  25. if (this.configService.authOptions.tokenMethod === 'cookie') {
  26. const cookieHandler = cookieSession({
  27. name: 'session',
  28. secret: this.configService.authOptions.sessionSecret,
  29. httpOnly: true,
  30. });
  31. defaultMiddleware.push({ handler: cookieHandler, route: adminApiPath });
  32. defaultMiddleware.push({ handler: cookieHandler, route: shopApiPath });
  33. }
  34. const allMiddleware = defaultMiddleware.concat(this.configService.middleware);
  35. const middlewareByRoute = this.groupMiddlewareByRoute(allMiddleware);
  36. for (const [route, handlers] of Object.entries(middlewareByRoute)) {
  37. consumer.apply(...handlers).forRoutes(route);
  38. }
  39. }
  40. async onModuleDestroy() {
  41. for (const plugin of this.configService.plugins) {
  42. if (plugin.onClose) {
  43. await plugin.onClose();
  44. }
  45. }
  46. }
  47. /**
  48. * Groups middleware handlers together in an object with the route as the key.
  49. */
  50. private groupMiddlewareByRoute(
  51. middlewareArray: Array<{ handler: RequestHandler; route?: string }>,
  52. ): { [route: string]: RequestHandler[] } {
  53. const result = {} as { [route: string]: RequestHandler[] };
  54. for (const middleware of middlewareArray) {
  55. const route = middleware.route || this.configService.adminApiPath;
  56. if (!result[route]) {
  57. result[route] = [];
  58. }
  59. result[route].push(middleware.handler);
  60. }
  61. return result;
  62. }
  63. }