bootstrap.ts 2.3 KB

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