bootstrap.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. const tcpServer = (workerApp as any).server.server;
  121. if (tcpServer) {
  122. tcpServer.on('error', (e: any) => {
  123. reject(e);
  124. });
  125. }
  126. workerApp.listenAsync().then(resolve);
  127. });
  128. workerWelcomeMessage(config);
  129. return workerApp;
  130. }
  131. /**
  132. * Setting the global config must be done prior to loading the AppModule.
  133. */
  134. export async function preBootstrapConfig(
  135. userConfig: Partial<VendureConfig>,
  136. ): Promise<ReadOnlyRequired<VendureConfig>> {
  137. if (userConfig) {
  138. setConfig(userConfig);
  139. }
  140. const entities = await getAllEntities(userConfig);
  141. const { coreSubscribersMap } = await import('./entity/subscribers');
  142. setConfig({
  143. dbConnectionOptions: {
  144. entities,
  145. subscribers: Object.values(coreSubscribersMap) as Array<Type<EntitySubscriberInterface>>,
  146. },
  147. });
  148. let config = getConfig();
  149. setEntityIdStrategy(config.entityIdStrategy, entities);
  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(config: RuntimeVendureConfig): Promise<RuntimeVendureConfig> {
  164. for (const plugin of config.plugins) {
  165. const configFn = getConfigurationFunction(plugin);
  166. if (typeof configFn === 'function') {
  167. config = await configFn(config);
  168. }
  169. }
  170. return config;
  171. }
  172. /**
  173. * Returns an array of core entities and any additional entities defined in plugins.
  174. */
  175. export async function getAllEntities(userConfig: Partial<VendureConfig>): Promise<Array<Type<any>>> {
  176. const coreEntities = Object.values(coreEntitiesMap) as Array<Type<any>>;
  177. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  178. const allEntities: Array<Type<any>> = coreEntities;
  179. // Check to ensure that no plugins are defining entities with names
  180. // which conflict with existing entities.
  181. for (const pluginEntity of pluginEntities) {
  182. if (allEntities.find(e => e.name === pluginEntity.name)) {
  183. throw new InternalServerError(`error.entity-name-conflict`, { entityName: pluginEntity.name });
  184. } else {
  185. allEntities.push(pluginEntity);
  186. }
  187. }
  188. return allEntities;
  189. }
  190. /**
  191. * If the 'bearer' tokenMethod is being used, then we automatically expose the authTokenHeaderKey header
  192. * in the CORS options, making sure to preserve any user-configured exposedHeaders.
  193. */
  194. function setExposedHeaders(config: ReadOnlyRequired<VendureConfig>) {
  195. if (config.authOptions.tokenMethod === 'bearer') {
  196. const authTokenHeaderKey = config.authOptions.authTokenHeaderKey as string;
  197. const corsOptions = config.cors;
  198. if (typeof corsOptions !== 'boolean') {
  199. const { exposedHeaders } = corsOptions;
  200. let exposedHeadersWithAuthKey: string[];
  201. if (!exposedHeaders) {
  202. exposedHeadersWithAuthKey = [authTokenHeaderKey];
  203. } else if (typeof exposedHeaders === 'string') {
  204. exposedHeadersWithAuthKey = exposedHeaders
  205. .split(',')
  206. .map(x => x.trim())
  207. .concat(authTokenHeaderKey);
  208. } else {
  209. exposedHeadersWithAuthKey = exposedHeaders.concat(authTokenHeaderKey);
  210. }
  211. corsOptions.exposedHeaders = exposedHeadersWithAuthKey;
  212. }
  213. }
  214. }
  215. /**
  216. * Monkey-patches the app's .close() method to also close the worker microservice
  217. * instance too.
  218. */
  219. function closeWorkerOnAppClose(app: INestApplication, worker: INestMicroservice) {
  220. // A Nest app is a nested Proxy. By getting the prototype we are
  221. // able to access and override the actual close() method.
  222. const appPrototype = Object.getPrototypeOf(app);
  223. const appClose = appPrototype.close.bind(app);
  224. appPrototype.close = async () => {
  225. await worker.close();
  226. await appClose();
  227. };
  228. }
  229. function workerWelcomeMessage(config: VendureConfig) {
  230. let transportString = '';
  231. let connectionString = '';
  232. const transport = (config.workerOptions && config.workerOptions.transport) || Transport.TCP;
  233. transportString = ` with ${Transport[transport]} transport`;
  234. const options = (config.workerOptions as TcpClientOptions).options;
  235. if (options) {
  236. const { host, port } = options;
  237. connectionString = ` at ${host || 'localhost'}:${port}`;
  238. }
  239. Logger.info(`Vendure Worker started${transportString}${connectionString}`);
  240. }
  241. function logWelcomeMessage(config: VendureConfig) {
  242. let version: string;
  243. try {
  244. version = require('../package.json').version;
  245. } catch (e) {
  246. version = ' unknown';
  247. }
  248. Logger.info(`=================================================`);
  249. Logger.info(`Vendure server (v${version}) now running on port ${config.port}`);
  250. Logger.info(`Shop API: http://localhost:${config.port}/${config.shopApiPath}`);
  251. Logger.info(`Admin API: http://localhost:${config.port}/${config.adminApiPath}`);
  252. logProxyMiddlewares(config);
  253. Logger.info(`=================================================`);
  254. }
  255. /**
  256. * Fix race condition when modifying DB
  257. * See: https://github.com/vendure-ecommerce/vendure/issues/152
  258. */
  259. function disableSynchronize(userConfig: ReadOnlyRequired<VendureConfig>): ReadOnlyRequired<VendureConfig> {
  260. const config = { ...userConfig };
  261. config.dbConnectionOptions = {
  262. ...userConfig.dbConnectionOptions,
  263. synchronize: false,
  264. } as ConnectionOptions;
  265. return config;
  266. }