bootstrap.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import { INestApplication, INestMicroservice } from '@nestjs/common';
  2. import { NestFactory } from '@nestjs/core';
  3. import { TcpClientOptions, Transport } from '@nestjs/microservices';
  4. import { Type } from '@vendure/common/lib/shared-types';
  5. import { EntitySubscriberInterface } from 'typeorm';
  6. import { InternalServerError } from './common/error/errors';
  7. import { ReadOnlyRequired } from './common/types/common-types';
  8. import { getConfig, setConfig } from './config/config-helpers';
  9. import { DefaultLogger } from './config/logger/default-logger';
  10. import { Logger } from './config/logger/vendure-logger';
  11. import { VendureConfig } from './config/vendure-config';
  12. import { registerCustomEntityFields } from './entity/register-custom-entity-fields';
  13. import { validateCustomFieldsConfig } from './entity/validate-custom-fields-config';
  14. import {
  15. getConfigurationFunction,
  16. getEntitiesFromPlugins,
  17. getPluginModules,
  18. hasLifecycleMethod,
  19. } from './plugin/plugin-metadata';
  20. import { logProxyMiddlewares } from './plugin/plugin-utils';
  21. export type VendureBootstrapFunction = (config: VendureConfig) => Promise<INestApplication>;
  22. /**
  23. * @description
  24. * Bootstraps the Vendure server. This is the entry point to the application.
  25. *
  26. * @example
  27. * ```TypeScript
  28. * import { bootstrap } from '\@vendure/core';
  29. * import { config } from './vendure-config';
  30. *
  31. * bootstrap(config).catch(err => {
  32. * console.log(err);
  33. * });
  34. * ```
  35. * @docsCategory
  36. * @docsWeight 0
  37. */
  38. export async function bootstrap(userConfig: Partial<VendureConfig>): Promise<INestApplication> {
  39. const config = await preBootstrapConfig(userConfig);
  40. Logger.useLogger(config.logger);
  41. Logger.info(`Bootstrapping Vendure Server (pid: ${process.pid})...`);
  42. // The AppModule *must* be loaded only after the entities have been set in the
  43. // config, so that they are available when the AppModule decorator is evaluated.
  44. // tslint:disable-next-line:whitespace
  45. const appModule = await import('./app.module');
  46. DefaultLogger.hideNestBoostrapLogs();
  47. const app = await NestFactory.create(appModule.AppModule, {
  48. cors: config.cors,
  49. logger: new Logger(),
  50. });
  51. DefaultLogger.restoreOriginalLogLevel();
  52. app.useLogger(new Logger());
  53. await app.listen(config.port, config.hostname);
  54. app.enableShutdownHooks();
  55. if (config.workerOptions.runInMainProcess) {
  56. const worker = await bootstrapWorkerInternal(config);
  57. Logger.warn(`Worker is running in main process. This is not recommended for production.`);
  58. Logger.warn(`[VendureConfig.workerOptions.runInMainProcess = true]`);
  59. closeWorkerOnAppClose(app, worker);
  60. }
  61. logWelcomeMessage(config);
  62. return app;
  63. }
  64. /**
  65. * @description
  66. * Bootstraps the Vendure worker. Read more about the [Vendure Worker]({{< relref "vendure-worker" >}}) or see the worker-specific options
  67. * defined in {@link WorkerOptions}.
  68. *
  69. * @example
  70. * ```TypeScript
  71. * import { bootstrapWorker } from '\@vendure/core';
  72. * import { config } from './vendure-config';
  73. *
  74. * bootstrapWorker(config).catch(err => {
  75. * console.log(err);
  76. * });
  77. * ```
  78. * @docsCategory worker
  79. * @docsWeight 0
  80. */
  81. export async function bootstrapWorker(userConfig: Partial<VendureConfig>): Promise<INestMicroservice> {
  82. if (userConfig.workerOptions && userConfig.workerOptions.runInMainProcess === true) {
  83. Logger.useLogger(userConfig.logger || new DefaultLogger());
  84. const errorMessage = `Cannot bootstrap worker when "runInMainProcess" is set to true`;
  85. Logger.error(errorMessage, 'Vendure Worker');
  86. throw new Error(errorMessage);
  87. } else {
  88. return bootstrapWorkerInternal(userConfig);
  89. }
  90. }
  91. async function bootstrapWorkerInternal(userConfig: Partial<VendureConfig>): Promise<INestMicroservice> {
  92. const config = await preBootstrapConfig(userConfig);
  93. if (!config.workerOptions.runInMainProcess && (config.logger as any).setDefaultContext) {
  94. (config.logger as any).setDefaultContext('Vendure Worker');
  95. }
  96. Logger.useLogger(config.logger);
  97. Logger.info(`Bootstrapping Vendure Worker (pid: ${process.pid})...`);
  98. const workerModule = await import('./worker/worker.module');
  99. DefaultLogger.hideNestBoostrapLogs();
  100. const workerApp = await NestFactory.createMicroservice(workerModule.WorkerModule, {
  101. transport: config.workerOptions.transport,
  102. logger: new Logger(),
  103. options: config.workerOptions.options,
  104. });
  105. DefaultLogger.restoreOriginalLogLevel();
  106. workerApp.useLogger(new Logger());
  107. workerApp.enableShutdownHooks();
  108. await workerApp.listenAsync();
  109. workerWelcomeMessage(config);
  110. return workerApp;
  111. }
  112. /**
  113. * Setting the global config must be done prior to loading the AppModule.
  114. */
  115. export async function preBootstrapConfig(
  116. userConfig: Partial<VendureConfig>,
  117. ): Promise<ReadOnlyRequired<VendureConfig>> {
  118. if (userConfig) {
  119. setConfig(userConfig);
  120. }
  121. // Entities *must* be loaded after the user config is set in order for the
  122. // base VendureEntity to be correctly configured with the primary key type
  123. // specified in the EntityIdStrategy.
  124. // tslint:disable-next-line:whitespace
  125. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  126. const entities = await getAllEntities(userConfig);
  127. const { coreSubscribersMap } = await import('./entity/subscribers');
  128. setConfig({
  129. dbConnectionOptions: {
  130. entities,
  131. subscribers: Object.values(coreSubscribersMap) as Array<Type<EntitySubscriberInterface>>,
  132. },
  133. });
  134. let config = getConfig();
  135. const customFieldValidationResult = validateCustomFieldsConfig(config.customFields, entities);
  136. if (!customFieldValidationResult.valid) {
  137. process.exitCode = 1;
  138. throw new Error(`CustomFields config error:\n- ` + customFieldValidationResult.errors.join('\n- '));
  139. }
  140. config = await runPluginConfigurations(config);
  141. registerCustomEntityFields(config);
  142. return config;
  143. }
  144. /**
  145. * Initialize any configured plugins.
  146. */
  147. async function runPluginConfigurations(
  148. config: ReadOnlyRequired<VendureConfig>,
  149. ): Promise<ReadOnlyRequired<VendureConfig>> {
  150. for (const plugin of config.plugins) {
  151. const configFn = getConfigurationFunction(plugin);
  152. if (typeof configFn === 'function') {
  153. config = await configFn(config);
  154. }
  155. }
  156. return config;
  157. }
  158. /**
  159. * Returns an array of core entities and any additional entities defined in plugins.
  160. */
  161. async function getAllEntities(userConfig: Partial<VendureConfig>): Promise<Array<Type<any>>> {
  162. const { coreEntitiesMap } = await import('./entity/entities');
  163. const coreEntities = Object.values(coreEntitiesMap) as Array<Type<any>>;
  164. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  165. const allEntities: Array<Type<any>> = coreEntities;
  166. // Check to ensure that no plugins are defining entities with names
  167. // which conflict with existing entities.
  168. for (const pluginEntity of pluginEntities) {
  169. if (allEntities.find(e => e.name === pluginEntity.name)) {
  170. throw new InternalServerError(`error.entity-name-conflict`, { entityName: pluginEntity.name });
  171. } else {
  172. allEntities.push(pluginEntity);
  173. }
  174. }
  175. return [...coreEntities, ...pluginEntities];
  176. }
  177. /**
  178. * Monkey-patches the app's .close() method to also close the worker microservice
  179. * instance too.
  180. */
  181. function closeWorkerOnAppClose(app: INestApplication, worker: INestMicroservice) {
  182. // A Nest app is a nested Proxy. By getting the prototype we are
  183. // able to access and override the actual close() method.
  184. const appPrototype = Object.getPrototypeOf(app);
  185. const appClose = appPrototype.close.bind(app);
  186. appPrototype.close = async () => {
  187. await worker.close();
  188. await appClose();
  189. };
  190. }
  191. function workerWelcomeMessage(config: VendureConfig) {
  192. let transportString = '';
  193. let connectionString = '';
  194. const transport = (config.workerOptions && config.workerOptions.transport) || Transport.TCP;
  195. transportString = ` with ${Transport[transport]} transport`;
  196. const options = (config.workerOptions as TcpClientOptions).options;
  197. if (options) {
  198. const { host, port } = options;
  199. connectionString = ` at ${host || 'localhost'}:${port}`;
  200. }
  201. Logger.info(`Vendure Worker started${transportString}${connectionString}`);
  202. }
  203. function logWelcomeMessage(config: VendureConfig) {
  204. let version: string;
  205. try {
  206. version = require('../package.json').version;
  207. } catch (e) {
  208. version = ' unknown';
  209. }
  210. Logger.info(`=================================================`);
  211. Logger.info(`Vendure server (v${version}) now running on port ${config.port}`);
  212. Logger.info(`Shop API: http://localhost:${config.port}/${config.shopApiPath}`);
  213. Logger.info(`Admin API: http://localhost:${config.port}/${config.adminApiPath}`);
  214. logProxyMiddlewares(config);
  215. Logger.info(`=================================================`);
  216. }