bootstrap.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { INestApplication } from '@nestjs/common';
  2. import { NestFactory } from '@nestjs/core';
  3. import { Type } from 'shared/shared-types';
  4. import { EntitySubscriberInterface } from 'typeorm';
  5. import { getConfig, setConfig, VendureConfig } from './config/vendure-config';
  6. import { VendureEntity } from './entity/base/base.entity';
  7. import { registerCustomEntityFields } from './entity/custom-entity-fields';
  8. export type VendureBootstrapFunction = (config: VendureConfig) => Promise<INestApplication>;
  9. /**
  10. * Bootstrap the Vendure server.
  11. */
  12. export async function bootstrap(userConfig: Partial<VendureConfig>): Promise<INestApplication> {
  13. const config = await preBootstrapConfig(userConfig);
  14. // The AppModule *must* be loaded only after the entities have been set in the
  15. // config, so that they are available when the AppModule decorator is evaluated.
  16. // tslint:disable-next-line:whitespace
  17. const appModule = await import('./app.module');
  18. const app = await NestFactory.create(appModule.AppModule, { cors: config.cors });
  19. return app.listen(config.port);
  20. }
  21. /**
  22. * Setting the global config must be done prior to loading the AppModule.
  23. */
  24. export async function preBootstrapConfig(userConfig: Partial<VendureConfig>): Promise<VendureConfig> {
  25. if (userConfig) {
  26. setConfig(userConfig);
  27. }
  28. // Entities *must* be loaded after the user config is set in order for the
  29. // base VendureEntity to be correctly configured with the primary key type
  30. // specified in the EntityIdStrategy.
  31. // tslint:disable-next-line:whitespace
  32. const { coreEntitiesMap } = await import('./entity/entities');
  33. const { coreSubscribersMap } = await import('./entity/subscribers');
  34. setConfig({
  35. dbConnectionOptions: {
  36. entities: Object.values(coreEntitiesMap) as Array<Type<VendureEntity>>,
  37. subscribers: Object.values(coreSubscribersMap) as Array<Type<EntitySubscriberInterface>>,
  38. },
  39. });
  40. const config = getConfig();
  41. registerCustomEntityFields(config);
  42. return config;
  43. }