bootstrap.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 { ConnectionOptions, 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 { RuntimeVendureConfig, VendureConfig } from './config/vendure-config';
  12. import { coreEntitiesMap } from './entity/entities';
  13. import { registerCustomEntityFields } from './entity/register-custom-entity-fields';
  14. import { setEntityIdStrategy } from './entity/set-entity-id-strategy';
  15. import { validateCustomFieldsConfig } from './entity/validate-custom-fields-config';
  16. import { getConfigurationFunction, getEntitiesFromPlugins } from './plugin/plugin-metadata';
  17. import { logProxyMiddlewares } from './plugin/plugin-utils';
  18. export type VendureBootstrapFunction = (config: VendureConfig) => Promise<INestApplication>;
  19. /**
  20. * @description
  21. * Bootstraps the Vendure server. This is the entry point to the application.
  22. *
  23. * @example
  24. * ```TypeScript
  25. * import { bootstrap } from '\@vendure/core';
  26. * import { config } from './vendure-config';
  27. *
  28. * bootstrap(config).catch(err => {
  29. * console.log(err);
  30. * });
  31. * ```
  32. * @docsCategory
  33. * */
  34. export async function bootstrap(userConfig: Partial<VendureConfig>): Promise<INestApplication> {
  35. const config = await preBootstrapConfig(userConfig);
  36. Logger.useLogger(config.logger);
  37. Logger.info(`Bootstrapping Vendure Server (pid: ${process.pid})...`);
  38. // The AppModule *must* be loaded only after the entities have been set in the
  39. // config, so that they are available when the AppModule decorator is evaluated.
  40. // tslint:disable-next-line:whitespace
  41. const appModule = await import('./app.module');
  42. DefaultLogger.hideNestBoostrapLogs();
  43. const app = await NestFactory.create(appModule.AppModule, {
  44. cors: config.cors,
  45. logger: new Logger(),
  46. });
  47. DefaultLogger.restoreOriginalLogLevel();
  48. app.useLogger(new Logger());
  49. await app.listen(config.port, config.hostname);
  50. app.enableShutdownHooks();
  51. if (config.workerOptions.runInMainProcess) {
  52. try {
  53. const worker = await bootstrapWorkerInternal(config);
  54. Logger.warn(`Worker is running in main process. This is not recommended for production.`);
  55. Logger.warn(`[VendureConfig.workerOptions.runInMainProcess = true]`);
  56. closeWorkerOnAppClose(app, worker);
  57. } catch (e) {
  58. Logger.error(`Could not start the worker process: ${e.message}`, 'Vendure Worker');
  59. }
  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. * */
  80. export async function bootstrapWorker(userConfig: Partial<VendureConfig>): Promise<INestMicroservice> {
  81. if (userConfig.workerOptions && userConfig.workerOptions.runInMainProcess === true) {
  82. Logger.useLogger(userConfig.logger || new DefaultLogger());
  83. const errorMessage = `Cannot bootstrap worker when "runInMainProcess" is set to true`;
  84. Logger.error(errorMessage, 'Vendure Worker');
  85. throw new Error(errorMessage);
  86. } else {
  87. try {
  88. const vendureConfig = await preBootstrapConfig(userConfig);
  89. return await bootstrapWorkerInternal(vendureConfig);
  90. } catch (e) {
  91. Logger.error(`Could not start the worker process: ${e.message}`, 'Vendure Worker');
  92. throw e;
  93. }
  94. }
  95. }
  96. async function bootstrapWorkerInternal(
  97. vendureConfig: ReadOnlyRequired<VendureConfig>,
  98. ): Promise<INestMicroservice> {
  99. const config = disableSynchronize(vendureConfig);
  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. const entities = await getAllEntities(userConfig);
  138. const { coreSubscribersMap } = await import('./entity/subscribers');
  139. setConfig({
  140. dbConnectionOptions: {
  141. entities,
  142. subscribers: Object.values(coreSubscribersMap) as Array<Type<EntitySubscriberInterface>>,
  143. },
  144. });
  145. let config = getConfig();
  146. setEntityIdStrategy(config.entityIdStrategy, entities);
  147. const customFieldValidationResult = validateCustomFieldsConfig(config.customFields, entities);
  148. if (!customFieldValidationResult.valid) {
  149. process.exitCode = 1;
  150. throw new Error(`CustomFields config error:\n- ` + customFieldValidationResult.errors.join('\n- '));
  151. }
  152. config = await runPluginConfigurations(config);
  153. registerCustomEntityFields(config);
  154. setExposedHeaders(config);
  155. return config;
  156. }
  157. /**
  158. * Initialize any configured plugins.
  159. */
  160. async function runPluginConfigurations(config: RuntimeVendureConfig): Promise<RuntimeVendureConfig> {
  161. for (const plugin of config.plugins) {
  162. const configFn = getConfigurationFunction(plugin);
  163. if (typeof configFn === 'function') {
  164. config = await configFn(config);
  165. }
  166. }
  167. return config;
  168. }
  169. /**
  170. * Returns an array of core entities and any additional entities defined in plugins.
  171. */
  172. export async function getAllEntities(userConfig: Partial<VendureConfig>): Promise<Array<Type<any>>> {
  173. const coreEntities = Object.values(coreEntitiesMap) as Array<Type<any>>;
  174. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  175. const allEntities: Array<Type<any>> = coreEntities;
  176. // Check to ensure that no plugins are defining entities with names
  177. // which conflict with existing entities.
  178. for (const pluginEntity of pluginEntities) {
  179. if (allEntities.find(e => e.name === pluginEntity.name)) {
  180. throw new InternalServerError(`error.entity-name-conflict`, { entityName: pluginEntity.name });
  181. } else {
  182. allEntities.push(pluginEntity);
  183. }
  184. }
  185. return allEntities;
  186. }
  187. /**
  188. * If the 'bearer' tokenMethod is being used, then we automatically expose the authTokenHeaderKey header
  189. * in the CORS options, making sure to preserve any user-configured exposedHeaders.
  190. */
  191. function setExposedHeaders(config: ReadOnlyRequired<VendureConfig>) {
  192. if (config.authOptions.tokenMethod === 'bearer') {
  193. const authTokenHeaderKey = config.authOptions.authTokenHeaderKey as string;
  194. const corsOptions = config.cors;
  195. if (typeof corsOptions !== 'boolean') {
  196. const { exposedHeaders } = corsOptions;
  197. let exposedHeadersWithAuthKey: string[];
  198. if (!exposedHeaders) {
  199. exposedHeadersWithAuthKey = [authTokenHeaderKey];
  200. } else if (typeof exposedHeaders === 'string') {
  201. exposedHeadersWithAuthKey = exposedHeaders
  202. .split(',')
  203. .map(x => x.trim())
  204. .concat(authTokenHeaderKey);
  205. } else {
  206. exposedHeadersWithAuthKey = exposedHeaders.concat(authTokenHeaderKey);
  207. }
  208. corsOptions.exposedHeaders = exposedHeadersWithAuthKey;
  209. }
  210. }
  211. }
  212. /**
  213. * Monkey-patches the app's .close() method to also close the worker microservice
  214. * instance too.
  215. */
  216. function closeWorkerOnAppClose(app: INestApplication, worker: INestMicroservice) {
  217. // A Nest app is a nested Proxy. By getting the prototype we are
  218. // able to access and override the actual close() method.
  219. const appPrototype = Object.getPrototypeOf(app);
  220. const appClose = appPrototype.close.bind(app);
  221. appPrototype.close = async () => {
  222. await worker.close();
  223. await appClose();
  224. };
  225. }
  226. function workerWelcomeMessage(config: VendureConfig) {
  227. let transportString = '';
  228. let connectionString = '';
  229. const transport = (config.workerOptions && config.workerOptions.transport) || Transport.TCP;
  230. transportString = ` with ${Transport[transport]} transport`;
  231. const options = (config.workerOptions as TcpClientOptions).options;
  232. if (options) {
  233. const { host, port } = options;
  234. connectionString = ` at ${host || 'localhost'}:${port}`;
  235. }
  236. Logger.info(`Vendure Worker started${transportString}${connectionString}`);
  237. }
  238. function logWelcomeMessage(config: VendureConfig) {
  239. let version: string;
  240. try {
  241. version = require('../package.json').version;
  242. } catch (e) {
  243. version = ' unknown';
  244. }
  245. Logger.info(`=================================================`);
  246. Logger.info(`Vendure server (v${version}) now running on port ${config.port}`);
  247. Logger.info(`Shop API: http://localhost:${config.port}/${config.shopApiPath}`);
  248. Logger.info(`Admin API: http://localhost:${config.port}/${config.adminApiPath}`);
  249. logProxyMiddlewares(config);
  250. Logger.info(`=================================================`);
  251. }
  252. /**
  253. * Fix race condition when modifying DB
  254. * See: https://github.com/vendure-ecommerce/vendure/issues/152
  255. */
  256. function disableSynchronize(userConfig: ReadOnlyRequired<VendureConfig>): ReadOnlyRequired<VendureConfig> {
  257. const config = { ...userConfig };
  258. config.dbConnectionOptions = {
  259. ...userConfig.dbConnectionOptions,
  260. synchronize: false,
  261. } as ConnectionOptions;
  262. return config;
  263. }