bootstrap.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import { INestApplication, INestApplicationContext } from '@nestjs/common';
  2. import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';
  3. import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
  4. import { NestFactory } from '@nestjs/core';
  5. import { getConnectionToken } from '@nestjs/typeorm';
  6. import { DEFAULT_COOKIE_NAME } from '@vendure/common/lib/shared-constants';
  7. import { Type } from '@vendure/common/lib/shared-types';
  8. import cookieSession = require('cookie-session');
  9. import { satisfies } from 'semver';
  10. import { Connection, DataSourceOptions, EntitySubscriberInterface } from 'typeorm';
  11. import { InternalServerError } from './common/error/errors';
  12. import { getConfig, setConfig } from './config/config-helpers';
  13. import { DefaultLogger } from './config/logger/default-logger';
  14. import { Logger } from './config/logger/vendure-logger';
  15. import { RuntimeVendureConfig, VendureConfig } from './config/vendure-config';
  16. import { Administrator } from './entity/administrator/administrator.entity';
  17. import { coreEntitiesMap } from './entity/entities';
  18. import { registerCustomEntityFields } from './entity/register-custom-entity-fields';
  19. import { runEntityMetadataModifiers } from './entity/run-entity-metadata-modifiers';
  20. import { setEntityIdStrategy } from './entity/set-entity-id-strategy';
  21. import { setMoneyStrategy } from './entity/set-money-strategy';
  22. import { validateCustomFieldsConfig } from './entity/validate-custom-fields-config';
  23. import { getCompatibility, getConfigurationFunction, getEntitiesFromPlugins } from './plugin/plugin-metadata';
  24. import { getPluginStartupMessages } from './plugin/plugin-utils';
  25. import { setProcessContext } from './process-context/process-context';
  26. import { VENDURE_VERSION } from './version';
  27. import { VendureWorker } from './worker/vendure-worker';
  28. export type VendureBootstrapFunction = (config: VendureConfig) => Promise<INestApplication>;
  29. /**
  30. * @description
  31. * Additional options that can be used to configure the bootstrap process of the
  32. * Vendure server.
  33. *
  34. * @since 2.2.0
  35. * @docsCategory common
  36. * @docsPage bootstrap
  37. */
  38. export interface BootstrapOptions {
  39. /**
  40. * @description
  41. * These options get passed directly to the `NestFactory.create()` method.
  42. */
  43. nestApplicationOptions: NestApplicationOptions;
  44. }
  45. /**
  46. * @description
  47. * Additional options that can be used to configure the bootstrap process of the
  48. * Vendure worker.
  49. *
  50. * @since 2.2.0
  51. * @docsCategory worker
  52. * @docsPage bootstrapWorker
  53. */
  54. export interface BootstrapWorkerOptions {
  55. /**
  56. * @description
  57. * These options get passed directly to the `NestFactory.createApplicationContext` method.
  58. */
  59. nestApplicationContextOptions: NestApplicationContextOptions;
  60. }
  61. /**
  62. * @description
  63. * Bootstraps the Vendure server. This is the entry point to the application.
  64. *
  65. * @example
  66. * ```ts
  67. * import { bootstrap } from '\@vendure/core';
  68. * import { config } from './vendure-config';
  69. *
  70. * bootstrap(config).catch(err => {
  71. * console.log(err);
  72. * process.exit(1);
  73. * });
  74. * ```
  75. *
  76. * ### Passing additional options
  77. *
  78. * Since v2.2.0, you can pass additional options to the NestJs application via the `options` parameter.
  79. * For example, to integrate with the [Nest Devtools](https://docs.nestjs.com/devtools/overview), you need to
  80. * pass the `snapshot` option:
  81. *
  82. * ```ts
  83. * import { bootstrap } from '\@vendure/core';
  84. * import { config } from './vendure-config';
  85. *
  86. * bootstrap(config, {
  87. * // highlight-start
  88. * nestApplicationOptions: {
  89. * snapshot: true,
  90. * }
  91. * // highlight-end
  92. * }).catch(err => {
  93. * console.log(err);
  94. * process.exit(1);
  95. * });
  96. * ```
  97. * @docsCategory common
  98. * @docsPage bootstrap
  99. * @docsWeight 0
  100. * */
  101. export async function bootstrap(
  102. userConfig: Partial<VendureConfig>,
  103. options?: BootstrapOptions,
  104. ): Promise<INestApplication> {
  105. const config = await preBootstrapConfig(userConfig);
  106. Logger.useLogger(config.logger);
  107. Logger.info(`Bootstrapping Vendure Server (pid: ${process.pid})...`);
  108. checkPluginCompatibility(config);
  109. // The AppModule *must* be loaded only after the entities have been set in the
  110. // config, so that they are available when the AppModule decorator is evaluated.
  111. // eslint-disable-next-line
  112. const appModule = await import('./app.module.js');
  113. setProcessContext('server');
  114. const { hostname, port, cors, middleware } = config.apiOptions;
  115. DefaultLogger.hideNestBoostrapLogs();
  116. const app = await NestFactory.create(appModule.AppModule, {
  117. cors,
  118. logger: new Logger(),
  119. ...options?.nestApplicationOptions,
  120. });
  121. DefaultLogger.restoreOriginalLogLevel();
  122. app.useLogger(new Logger());
  123. const { tokenMethod } = config.authOptions;
  124. const usingCookie =
  125. tokenMethod === 'cookie' || (Array.isArray(tokenMethod) && tokenMethod.includes('cookie'));
  126. if (usingCookie) {
  127. configureSessionCookies(app, config);
  128. }
  129. const earlyMiddlewares = middleware.filter(mid => mid.beforeListen);
  130. earlyMiddlewares.forEach(mid => {
  131. app.use(mid.route, mid.handler);
  132. });
  133. await app.listen(port, hostname || '');
  134. app.enableShutdownHooks();
  135. logWelcomeMessage(config);
  136. return app;
  137. }
  138. /**
  139. * @description
  140. * Bootstraps a Vendure worker. Resolves to a {@link VendureWorker} object containing a reference to the underlying
  141. * NestJs [standalone application](https://docs.nestjs.com/standalone-applications) as well as convenience
  142. * methods for starting the job queue and health check server.
  143. *
  144. * Read more about the [Vendure Worker](/guides/developer-guide/worker-job-queue/).
  145. *
  146. * @example
  147. * ```ts
  148. * import { bootstrapWorker } from '\@vendure/core';
  149. * import { config } from './vendure-config';
  150. *
  151. * bootstrapWorker(config)
  152. * .then(worker => worker.startJobQueue())
  153. * .then(worker => worker.startHealthCheckServer({ port: 3020 }))
  154. * .catch(err => {
  155. * console.log(err);
  156. * process.exit(1);
  157. * });
  158. * ```
  159. * @docsCategory worker
  160. * @docsPage bootstrapWorker
  161. * @docsWeight 0
  162. * */
  163. export async function bootstrapWorker(
  164. userConfig: Partial<VendureConfig>,
  165. options?: BootstrapWorkerOptions,
  166. ): Promise<VendureWorker> {
  167. const vendureConfig = await preBootstrapConfig(userConfig);
  168. const config = disableSynchronize(vendureConfig);
  169. config.logger.setDefaultContext?.('Vendure Worker');
  170. Logger.useLogger(config.logger);
  171. Logger.info(`Bootstrapping Vendure Worker (pid: ${process.pid})...`);
  172. checkPluginCompatibility(config);
  173. setProcessContext('worker');
  174. DefaultLogger.hideNestBoostrapLogs();
  175. const WorkerModule = await import('./worker/worker.module.js').then(m => m.WorkerModule);
  176. const workerApp = await NestFactory.createApplicationContext(WorkerModule, {
  177. logger: new Logger(),
  178. ...options?.nestApplicationContextOptions,
  179. });
  180. DefaultLogger.restoreOriginalLogLevel();
  181. workerApp.useLogger(new Logger());
  182. workerApp.enableShutdownHooks();
  183. await validateDbTablesForWorker(workerApp);
  184. Logger.info('Vendure Worker is ready');
  185. return new VendureWorker(workerApp);
  186. }
  187. /**
  188. * Setting the global config must be done prior to loading the AppModule.
  189. */
  190. export async function preBootstrapConfig(
  191. userConfig: Partial<VendureConfig>,
  192. ): Promise<Readonly<RuntimeVendureConfig>> {
  193. if (userConfig) {
  194. await setConfig(userConfig);
  195. }
  196. const entities = getAllEntities(userConfig);
  197. const { coreSubscribersMap } = await import('./entity/subscribers.js');
  198. await setConfig({
  199. dbConnectionOptions: {
  200. entities,
  201. subscribers: [
  202. ...((userConfig.dbConnectionOptions?.subscribers ?? []) as Array<
  203. Type<EntitySubscriberInterface>
  204. >),
  205. ...(Object.values(coreSubscribersMap) as Array<Type<EntitySubscriberInterface>>),
  206. ],
  207. },
  208. });
  209. let config = getConfig();
  210. // The logger is set here so that we are able to log any messages prior to the final
  211. // logger (which may depend on config coming from a plugin) being set.
  212. Logger.useLogger(config.logger);
  213. config = await runPluginConfigurations(config);
  214. const entityIdStrategy = config.entityOptions.entityIdStrategy ?? config.entityIdStrategy;
  215. setEntityIdStrategy(entityIdStrategy, entities);
  216. const moneyStrategy = config.entityOptions.moneyStrategy;
  217. setMoneyStrategy(moneyStrategy, entities);
  218. const customFieldValidationResult = validateCustomFieldsConfig(config.customFields, entities);
  219. if (!customFieldValidationResult.valid) {
  220. process.exitCode = 1;
  221. throw new Error('CustomFields config error:\n- ' + customFieldValidationResult.errors.join('\n- '));
  222. }
  223. registerCustomEntityFields(config);
  224. await runEntityMetadataModifiers(config);
  225. setExposedHeaders(config);
  226. return config;
  227. }
  228. function checkPluginCompatibility(config: RuntimeVendureConfig): void {
  229. for (const plugin of config.plugins) {
  230. const compatibility = getCompatibility(plugin);
  231. const pluginName = (plugin as any).name as string;
  232. if (!compatibility) {
  233. Logger.info(
  234. `The plugin "${pluginName}" does not specify a compatibility range, so it is not guaranteed to be compatible with this version of Vendure.`,
  235. );
  236. } else {
  237. if (!satisfies(VENDURE_VERSION, compatibility, { loose: true, includePrerelease: true })) {
  238. Logger.error(
  239. `Plugin "${pluginName}" is not compatible with this version of Vendure. ` +
  240. `It specifies a semver range of "${compatibility}" but the current version is "${VENDURE_VERSION}".`,
  241. );
  242. throw new InternalServerError(
  243. `Plugin "${pluginName}" is not compatible with this version of Vendure.`,
  244. );
  245. }
  246. }
  247. }
  248. }
  249. /**
  250. * Initialize any configured plugins.
  251. */
  252. async function runPluginConfigurations(config: RuntimeVendureConfig): Promise<RuntimeVendureConfig> {
  253. for (const plugin of config.plugins) {
  254. const configFn = getConfigurationFunction(plugin);
  255. if (typeof configFn === 'function') {
  256. const result = await configFn(config);
  257. Object.assign(config, result);
  258. }
  259. }
  260. return config;
  261. }
  262. /**
  263. * Returns an array of core entities and any additional entities defined in plugins.
  264. */
  265. export function getAllEntities(userConfig: Partial<VendureConfig>): Array<Type<any>> {
  266. const coreEntities = Object.values(coreEntitiesMap) as Array<Type<any>>;
  267. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  268. const allEntities: Array<Type<any>> = coreEntities;
  269. // Check to ensure that no plugins are defining entities with names
  270. // which conflict with existing entities.
  271. for (const pluginEntity of pluginEntities) {
  272. if (allEntities.find(e => e.name === pluginEntity.name)) {
  273. throw new InternalServerError('error.entity-name-conflict', { entityName: pluginEntity.name });
  274. } else {
  275. allEntities.push(pluginEntity);
  276. }
  277. }
  278. return allEntities;
  279. }
  280. /**
  281. * If the 'bearer' tokenMethod is being used, then we automatically expose the authTokenHeaderKey header
  282. * in the CORS options, making sure to preserve any user-configured exposedHeaders.
  283. */
  284. function setExposedHeaders(config: Readonly<RuntimeVendureConfig>) {
  285. const { tokenMethod } = config.authOptions;
  286. const isUsingBearerToken =
  287. tokenMethod === 'bearer' || (Array.isArray(tokenMethod) && tokenMethod.includes('bearer'));
  288. if (isUsingBearerToken) {
  289. const authTokenHeaderKey = config.authOptions.authTokenHeaderKey;
  290. const corsOptions = config.apiOptions.cors;
  291. if (typeof corsOptions !== 'boolean') {
  292. const { exposedHeaders } = corsOptions;
  293. let exposedHeadersWithAuthKey: string[];
  294. if (!exposedHeaders) {
  295. exposedHeadersWithAuthKey = [authTokenHeaderKey];
  296. } else if (typeof exposedHeaders === 'string') {
  297. exposedHeadersWithAuthKey = exposedHeaders
  298. .split(',')
  299. .map(x => x.trim())
  300. .concat(authTokenHeaderKey);
  301. } else {
  302. exposedHeadersWithAuthKey = exposedHeaders.concat(authTokenHeaderKey);
  303. }
  304. corsOptions.exposedHeaders = exposedHeadersWithAuthKey;
  305. }
  306. }
  307. }
  308. function logWelcomeMessage(config: RuntimeVendureConfig) {
  309. const { port, shopApiPath, adminApiPath, hostname } = config.apiOptions;
  310. const apiCliGreetings: Array<readonly [string, string]> = [];
  311. const pathToUrl = (path: string) => `http://${hostname || 'localhost'}:${port}/${path}`;
  312. apiCliGreetings.push(['Shop API', pathToUrl(shopApiPath)]);
  313. apiCliGreetings.push(['Admin API', pathToUrl(adminApiPath)]);
  314. apiCliGreetings.push(
  315. ...getPluginStartupMessages().map(({ label, path }) => [label, pathToUrl(path)] as const),
  316. );
  317. const columnarGreetings = arrangeCliGreetingsInColumns(apiCliGreetings);
  318. const title = `Vendure server (v${VENDURE_VERSION}) now running on port ${port}`;
  319. const maxLineLength = Math.max(title.length, ...columnarGreetings.map(l => l.length));
  320. const titlePadLength = title.length < maxLineLength ? Math.floor((maxLineLength - title.length) / 2) : 0;
  321. Logger.info('='.repeat(maxLineLength));
  322. Logger.info(title.padStart(title.length + titlePadLength));
  323. Logger.info('-'.repeat(maxLineLength).padStart(titlePadLength));
  324. columnarGreetings.forEach(line => Logger.info(line));
  325. Logger.info('='.repeat(maxLineLength));
  326. }
  327. function arrangeCliGreetingsInColumns(lines: Array<readonly [string, string]>): string[] {
  328. const columnWidth = Math.max(...lines.map(l => l[0].length)) + 2;
  329. return lines.map(l => `${(l[0] + ':').padEnd(columnWidth)}${l[1]}`);
  330. }
  331. /**
  332. * Fix race condition when modifying DB
  333. * See: https://github.com/vendure-ecommerce/vendure/issues/152
  334. */
  335. function disableSynchronize(userConfig: Readonly<RuntimeVendureConfig>): Readonly<RuntimeVendureConfig> {
  336. const config = {
  337. ...userConfig,
  338. dbConnectionOptions: {
  339. ...userConfig.dbConnectionOptions,
  340. synchronize: false,
  341. } as DataSourceOptions,
  342. };
  343. return config;
  344. }
  345. /**
  346. * Check that the Database tables exist. When running Vendure server & worker
  347. * concurrently for the first time, the worker will attempt to access the
  348. * DB tables before the server has populated them (assuming synchronize = true
  349. * in config). This method will use polling to check the existence of a known table
  350. * before allowing the rest of the worker bootstrap to continue.
  351. * @param worker
  352. */
  353. async function validateDbTablesForWorker(worker: INestApplicationContext) {
  354. const connection: Connection = worker.get(getConnectionToken());
  355. await new Promise<void>(async (resolve, reject) => {
  356. const checkForTables = async (): Promise<boolean> => {
  357. try {
  358. const adminCount = await connection.getRepository(Administrator).count();
  359. return 0 < adminCount;
  360. } catch (e: any) {
  361. return false;
  362. }
  363. };
  364. const pollIntervalMs = 5000;
  365. let attempts = 0;
  366. const maxAttempts = 10;
  367. let validTableStructure = false;
  368. Logger.verbose('Checking for expected DB table structure...');
  369. while (!validTableStructure && attempts < maxAttempts) {
  370. attempts++;
  371. validTableStructure = await checkForTables();
  372. if (validTableStructure) {
  373. Logger.verbose('Table structure verified');
  374. resolve();
  375. return;
  376. }
  377. Logger.verbose(
  378. `Table structure could not be verified, trying again after ${pollIntervalMs}ms (attempt ${attempts} of ${maxAttempts})`,
  379. );
  380. await new Promise(resolve1 => setTimeout(resolve1, pollIntervalMs));
  381. }
  382. reject('Could not validate DB table structure. Aborting bootstrap.');
  383. });
  384. }
  385. export function configureSessionCookies(
  386. app: INestApplication,
  387. userConfig: Readonly<RuntimeVendureConfig>,
  388. ): void {
  389. const { cookieOptions } = userConfig.authOptions;
  390. // Globally set the cookie session middleware
  391. const cookieName =
  392. typeof cookieOptions?.name !== 'string' ? cookieOptions.name?.shop : cookieOptions.name;
  393. app.use(
  394. cookieSession({
  395. ...cookieOptions,
  396. name: cookieName ?? DEFAULT_COOKIE_NAME,
  397. }),
  398. );
  399. }