bootstrap.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. * */
  37. export async function bootstrap(userConfig: Partial<VendureConfig>): Promise<INestApplication> {
  38. const config = await preBootstrapConfig(userConfig);
  39. Logger.useLogger(config.logger);
  40. Logger.info(`Bootstrapping Vendure Server (pid: ${process.pid})...`);
  41. // The AppModule *must* be loaded only after the entities have been set in the
  42. // config, so that they are available when the AppModule decorator is evaluated.
  43. // tslint:disable-next-line:whitespace
  44. const appModule = await import('./app.module');
  45. DefaultLogger.hideNestBoostrapLogs();
  46. const app = await NestFactory.create(appModule.AppModule, {
  47. cors: config.cors,
  48. logger: new Logger(),
  49. });
  50. DefaultLogger.restoreOriginalLogLevel();
  51. app.useLogger(new Logger());
  52. await app.listen(config.port, config.hostname);
  53. app.enableShutdownHooks();
  54. if (config.workerOptions.runInMainProcess) {
  55. try {
  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. } catch (e) {
  61. Logger.error(`Could not start the worker process: ${e.message}`, 'Vendure Worker');
  62. }
  63. }
  64. logWelcomeMessage(config);
  65. return app;
  66. }
  67. /**
  68. * @description
  69. * Bootstraps the Vendure worker. Read more about the [Vendure Worker]({{< relref "vendure-worker" >}}) or see the worker-specific options
  70. * defined in {@link WorkerOptions}.
  71. *
  72. * @example
  73. * ```TypeScript
  74. * import { bootstrapWorker } from '\@vendure/core';
  75. * import { config } from './vendure-config';
  76. *
  77. * bootstrapWorker(config).catch(err => {
  78. * console.log(err);
  79. * });
  80. * ```
  81. * @docsCategory worker
  82. * */
  83. export async function bootstrapWorker(userConfig: Partial<VendureConfig>): Promise<INestMicroservice> {
  84. if (userConfig.workerOptions && userConfig.workerOptions.runInMainProcess === true) {
  85. Logger.useLogger(userConfig.logger || new DefaultLogger());
  86. const errorMessage = `Cannot bootstrap worker when "runInMainProcess" is set to true`;
  87. Logger.error(errorMessage, 'Vendure Worker');
  88. throw new Error(errorMessage);
  89. } else {
  90. try {
  91. return await bootstrapWorkerInternal(userConfig);
  92. } catch (e) {
  93. Logger.error(`Could not start the worker process: ${e.message}`, 'Vendure Worker');
  94. throw e;
  95. }
  96. }
  97. }
  98. async function bootstrapWorkerInternal(userConfig: Partial<VendureConfig>): Promise<INestMicroservice> {
  99. const config = await preBootstrapConfig(userConfig);
  100. if (!config.workerOptions.runInMainProcess && (config.logger as any).setDefaultContext) {
  101. (config.logger as any).setDefaultContext('Vendure Worker');
  102. }
  103. Logger.useLogger(config.logger);
  104. Logger.info(`Bootstrapping Vendure Worker (pid: ${process.pid})...`);
  105. const workerModule = await import('./worker/worker.module');
  106. DefaultLogger.hideNestBoostrapLogs();
  107. const workerApp = await NestFactory.createMicroservice(workerModule.WorkerModule, {
  108. transport: config.workerOptions.transport,
  109. logger: new Logger(),
  110. options: config.workerOptions.options,
  111. });
  112. DefaultLogger.restoreOriginalLogLevel();
  113. workerApp.useLogger(new Logger());
  114. workerApp.enableShutdownHooks();
  115. // A work-around to correctly handle errors when attempting to start the
  116. // microservice server listening.
  117. // See https://github.com/nestjs/nest/issues/2777
  118. // TODO: Remove if & when the above issue is resolved.
  119. await new Promise((resolve, reject) => {
  120. (workerApp as any).server.server.on('error', (e: any) => {
  121. reject(e);
  122. });
  123. workerApp.listenAsync().then(resolve);
  124. });
  125. workerWelcomeMessage(config);
  126. return workerApp;
  127. }
  128. /**
  129. * Setting the global config must be done prior to loading the AppModule.
  130. */
  131. export async function preBootstrapConfig(
  132. userConfig: Partial<VendureConfig>,
  133. ): Promise<ReadOnlyRequired<VendureConfig>> {
  134. if (userConfig) {
  135. setConfig(userConfig);
  136. }
  137. // Entities *must* be loaded after the user config is set in order for the
  138. // base VendureEntity to be correctly configured with the primary key type
  139. // specified in the EntityIdStrategy.
  140. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  141. const entities = await getAllEntities(userConfig);
  142. const { coreSubscribersMap } = await import('./entity/subscribers');
  143. setConfig({
  144. dbConnectionOptions: {
  145. entities,
  146. subscribers: Object.values(coreSubscribersMap) as Array<Type<EntitySubscriberInterface>>,
  147. },
  148. });
  149. let config = getConfig();
  150. const customFieldValidationResult = validateCustomFieldsConfig(config.customFields, entities);
  151. if (!customFieldValidationResult.valid) {
  152. process.exitCode = 1;
  153. throw new Error(`CustomFields config error:\n- ` + customFieldValidationResult.errors.join('\n- '));
  154. }
  155. config = await runPluginConfigurations(config);
  156. registerCustomEntityFields(config);
  157. setExposedHeaders(config);
  158. return config;
  159. }
  160. /**
  161. * Initialize any configured plugins.
  162. */
  163. async function runPluginConfigurations(
  164. config: ReadOnlyRequired<VendureConfig>,
  165. ): Promise<ReadOnlyRequired<VendureConfig>> {
  166. for (const plugin of config.plugins) {
  167. const configFn = getConfigurationFunction(plugin);
  168. if (typeof configFn === 'function') {
  169. config = await configFn(config);
  170. }
  171. }
  172. return config;
  173. }
  174. /**
  175. * Returns an array of core entities and any additional entities defined in plugins.
  176. */
  177. async function getAllEntities(userConfig: Partial<VendureConfig>): Promise<Array<Type<any>>> {
  178. const { coreEntitiesMap } = await import('./entity/entities');
  179. const coreEntities = Object.values(coreEntitiesMap) as Array<Type<any>>;
  180. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  181. const allEntities: Array<Type<any>> = coreEntities;
  182. // Check to ensure that no plugins are defining entities with names
  183. // which conflict with existing entities.
  184. for (const pluginEntity of pluginEntities) {
  185. if (allEntities.find(e => e.name === pluginEntity.name)) {
  186. throw new InternalServerError(`error.entity-name-conflict`, { entityName: pluginEntity.name });
  187. } else {
  188. allEntities.push(pluginEntity);
  189. }
  190. }
  191. return [...coreEntities, ...pluginEntities];
  192. }
  193. /**
  194. * If the 'bearer' tokenMethod is being used, then we automatically expose the authTokenHeaderKey header
  195. * in the CORS options, making sure to preserve any user-configured exposedHeaders.
  196. */
  197. function setExposedHeaders(config: ReadOnlyRequired<VendureConfig>) {
  198. if (config.authOptions.tokenMethod === 'bearer') {
  199. const authTokenHeaderKey = config.authOptions.authTokenHeaderKey as string;
  200. const corsOptions = config.cors;
  201. if (typeof corsOptions !== 'boolean') {
  202. const { exposedHeaders } = corsOptions;
  203. let exposedHeadersWithAuthKey: string[];
  204. if (!exposedHeaders) {
  205. exposedHeadersWithAuthKey = [authTokenHeaderKey];
  206. } else if (typeof exposedHeaders === 'string') {
  207. exposedHeadersWithAuthKey = exposedHeaders
  208. .split(',')
  209. .map(x => x.trim())
  210. .concat(authTokenHeaderKey);
  211. } else {
  212. exposedHeadersWithAuthKey = exposedHeaders.concat(authTokenHeaderKey);
  213. }
  214. corsOptions.exposedHeaders = exposedHeadersWithAuthKey;
  215. }
  216. }
  217. }
  218. /**
  219. * Monkey-patches the app's .close() method to also close the worker microservice
  220. * instance too.
  221. */
  222. function closeWorkerOnAppClose(app: INestApplication, worker: INestMicroservice) {
  223. // A Nest app is a nested Proxy. By getting the prototype we are
  224. // able to access and override the actual close() method.
  225. const appPrototype = Object.getPrototypeOf(app);
  226. const appClose = appPrototype.close.bind(app);
  227. appPrototype.close = async () => {
  228. await worker.close();
  229. await appClose();
  230. };
  231. }
  232. function workerWelcomeMessage(config: VendureConfig) {
  233. let transportString = '';
  234. let connectionString = '';
  235. const transport = (config.workerOptions && config.workerOptions.transport) || Transport.TCP;
  236. transportString = ` with ${Transport[transport]} transport`;
  237. const options = (config.workerOptions as TcpClientOptions).options;
  238. if (options) {
  239. const { host, port } = options;
  240. connectionString = ` at ${host || 'localhost'}:${port}`;
  241. }
  242. Logger.info(`Vendure Worker started${transportString}${connectionString}`);
  243. }
  244. function logWelcomeMessage(config: VendureConfig) {
  245. let version: string;
  246. try {
  247. version = require('../package.json').version;
  248. } catch (e) {
  249. version = ' unknown';
  250. }
  251. Logger.info(`=================================================`);
  252. Logger.info(`Vendure server (v${version}) now running on port ${config.port}`);
  253. Logger.info(`Shop API: http://localhost:${config.port}/${config.shopApiPath}`);
  254. Logger.info(`Admin API: http://localhost:${config.port}/${config.adminApiPath}`);
  255. logProxyMiddlewares(config);
  256. Logger.info(`=================================================`);
  257. }