bootstrap.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import { INestApplication, INestApplicationContext } from '@nestjs/common';
  2. import { NestFactory } from '@nestjs/core';
  3. import { getConnectionToken } from '@nestjs/typeorm';
  4. import { Type } from '@vendure/common/lib/shared-types';
  5. import cookieSession = require('cookie-session');
  6. import { Connection, DataSourceOptions, EntitySubscriberInterface } from 'typeorm';
  7. import { InternalServerError } from './common/error/errors';
  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 { Administrator } from './entity/administrator/administrator.entity';
  13. import { coreEntitiesMap } from './entity/entities';
  14. import { registerCustomEntityFields } from './entity/register-custom-entity-fields';
  15. import { runEntityMetadataModifiers } from './entity/run-entity-metadata-modifiers';
  16. import { setEntityIdStrategy } from './entity/set-entity-id-strategy';
  17. import { setMoneyStrategy } from './entity/set-money-strategy';
  18. import { validateCustomFieldsConfig } from './entity/validate-custom-fields-config';
  19. import { getConfigurationFunction, getEntitiesFromPlugins } from './plugin/plugin-metadata';
  20. import { getPluginStartupMessages } from './plugin/plugin-utils';
  21. import { setProcessContext } from './process-context/process-context';
  22. import { VendureWorker } from './worker/vendure-worker';
  23. export type VendureBootstrapFunction = (config: VendureConfig) => Promise<INestApplication>;
  24. /**
  25. * @description
  26. * Bootstraps the Vendure server. This is the entry point to the application.
  27. *
  28. * @example
  29. * ```TypeScript
  30. * import { bootstrap } from '\@vendure/core';
  31. * import { config } from './vendure-config';
  32. *
  33. * bootstrap(config).catch(err => {
  34. * console.log(err);
  35. * });
  36. * ```
  37. * @docsCategory
  38. * */
  39. export async function bootstrap(userConfig: Partial<VendureConfig>): Promise<INestApplication> {
  40. const config = await preBootstrapConfig(userConfig);
  41. Logger.useLogger(config.logger);
  42. Logger.info(`Bootstrapping Vendure Server (pid: ${process.pid})...`);
  43. // The AppModule *must* be loaded only after the entities have been set in the
  44. // config, so that they are available when the AppModule decorator is evaluated.
  45. // eslint-disable-next-line
  46. const appModule = await import('./app.module.js');
  47. setProcessContext('server');
  48. const { hostname, port, cors, middleware } = config.apiOptions;
  49. DefaultLogger.hideNestBoostrapLogs();
  50. const app = await NestFactory.create(appModule.AppModule, {
  51. cors,
  52. logger: new Logger(),
  53. });
  54. DefaultLogger.restoreOriginalLogLevel();
  55. app.useLogger(new Logger());
  56. const { tokenMethod } = config.authOptions;
  57. const usingCookie =
  58. tokenMethod === 'cookie' || (Array.isArray(tokenMethod) && tokenMethod.includes('cookie'));
  59. if (usingCookie) {
  60. const { cookieOptions } = config.authOptions;
  61. app.use(cookieSession(cookieOptions));
  62. }
  63. const earlyMiddlewares = middleware.filter(mid => mid.beforeListen);
  64. earlyMiddlewares.forEach(mid => {
  65. app.use(mid.route, mid.handler);
  66. });
  67. await app.listen(port, hostname || '');
  68. app.enableShutdownHooks();
  69. logWelcomeMessage(config);
  70. return app;
  71. }
  72. /**
  73. * @description
  74. * Bootstraps a Vendure worker. Resolves to a {@link VendureWorker} object containing a reference to the underlying
  75. * NestJs [standalone application](https://docs.nestjs.com/standalone-applications) as well as convenience
  76. * methods for starting the job queue and health check server.
  77. *
  78. * Read more about the [Vendure Worker]({{< relref "vendure-worker" >}}).
  79. *
  80. * @example
  81. * ```TypeScript
  82. * import { bootstrapWorker } from '\@vendure/core';
  83. * import { config } from './vendure-config';
  84. *
  85. * bootstrapWorker(config)
  86. * .then(worker => worker.startJobQueue())
  87. * .then(worker => worker.startHealthCheckServer({ port: 3020 }))
  88. * .catch(err => {
  89. * console.log(err);
  90. * });
  91. * ```
  92. * @docsCategory worker
  93. * */
  94. export async function bootstrapWorker(userConfig: Partial<VendureConfig>): Promise<VendureWorker> {
  95. const vendureConfig = await preBootstrapConfig(userConfig);
  96. const config = disableSynchronize(vendureConfig);
  97. config.logger.setDefaultContext?.('Vendure Worker');
  98. Logger.useLogger(config.logger);
  99. Logger.info(`Bootstrapping Vendure Worker (pid: ${process.pid})...`);
  100. setProcessContext('worker');
  101. DefaultLogger.hideNestBoostrapLogs();
  102. const WorkerModule = await import('./worker/worker.module.js').then(m => m.WorkerModule);
  103. const workerApp = await NestFactory.createApplicationContext(WorkerModule, {
  104. logger: new Logger(),
  105. });
  106. DefaultLogger.restoreOriginalLogLevel();
  107. workerApp.useLogger(new Logger());
  108. workerApp.enableShutdownHooks();
  109. await validateDbTablesForWorker(workerApp);
  110. Logger.info('Vendure Worker is ready');
  111. return new VendureWorker(workerApp);
  112. }
  113. /**
  114. * Setting the global config must be done prior to loading the AppModule.
  115. */
  116. export async function preBootstrapConfig(
  117. userConfig: Partial<VendureConfig>,
  118. ): Promise<Readonly<RuntimeVendureConfig>> {
  119. if (userConfig) {
  120. await setConfig(userConfig);
  121. }
  122. const entities = await getAllEntities(userConfig);
  123. const { coreSubscribersMap } = await import('./entity/subscribers.js');
  124. await setConfig({
  125. dbConnectionOptions: {
  126. entities,
  127. subscribers: [
  128. ...((userConfig.dbConnectionOptions?.subscribers ?? []) as Array<
  129. Type<EntitySubscriberInterface>
  130. >),
  131. ...(Object.values(coreSubscribersMap) as Array<Type<EntitySubscriberInterface>>),
  132. ],
  133. },
  134. });
  135. let config = getConfig();
  136. const entityIdStrategy = config.entityOptions.entityIdStrategy ?? config.entityIdStrategy;
  137. setEntityIdStrategy(entityIdStrategy, entities);
  138. const moneyStrategy = config.entityOptions.moneyStrategy;
  139. setMoneyStrategy(moneyStrategy, entities);
  140. const customFieldValidationResult = validateCustomFieldsConfig(config.customFields, entities);
  141. if (!customFieldValidationResult.valid) {
  142. process.exitCode = 1;
  143. throw new Error('CustomFields config error:\n- ' + customFieldValidationResult.errors.join('\n- '));
  144. }
  145. config = await runPluginConfigurations(config);
  146. registerCustomEntityFields(config);
  147. await runEntityMetadataModifiers(config);
  148. setExposedHeaders(config);
  149. return config;
  150. }
  151. /**
  152. * Initialize any configured plugins.
  153. */
  154. async function runPluginConfigurations(config: RuntimeVendureConfig): Promise<RuntimeVendureConfig> {
  155. for (const plugin of config.plugins) {
  156. const configFn = getConfigurationFunction(plugin);
  157. if (typeof configFn === 'function') {
  158. config = await configFn(config);
  159. }
  160. }
  161. return config;
  162. }
  163. /**
  164. * Returns an array of core entities and any additional entities defined in plugins.
  165. */
  166. export async function getAllEntities(userConfig: Partial<VendureConfig>): Promise<Array<Type<any>>> {
  167. const coreEntities = Object.values(coreEntitiesMap) as Array<Type<any>>;
  168. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  169. const allEntities: Array<Type<any>> = coreEntities;
  170. // Check to ensure that no plugins are defining entities with names
  171. // which conflict with existing entities.
  172. for (const pluginEntity of pluginEntities) {
  173. if (allEntities.find(e => e.name === pluginEntity.name)) {
  174. throw new InternalServerError('error.entity-name-conflict', { entityName: pluginEntity.name });
  175. } else {
  176. allEntities.push(pluginEntity);
  177. }
  178. }
  179. return allEntities;
  180. }
  181. /**
  182. * If the 'bearer' tokenMethod is being used, then we automatically expose the authTokenHeaderKey header
  183. * in the CORS options, making sure to preserve any user-configured exposedHeaders.
  184. */
  185. function setExposedHeaders(config: Readonly<RuntimeVendureConfig>) {
  186. const { tokenMethod } = config.authOptions;
  187. const isUsingBearerToken =
  188. tokenMethod === 'bearer' || (Array.isArray(tokenMethod) && tokenMethod.includes('bearer'));
  189. if (isUsingBearerToken) {
  190. const authTokenHeaderKey = config.authOptions.authTokenHeaderKey;
  191. const corsOptions = config.apiOptions.cors;
  192. if (typeof corsOptions !== 'boolean') {
  193. const { exposedHeaders } = corsOptions;
  194. let exposedHeadersWithAuthKey: string[];
  195. if (!exposedHeaders) {
  196. exposedHeadersWithAuthKey = [authTokenHeaderKey];
  197. } else if (typeof exposedHeaders === 'string') {
  198. exposedHeadersWithAuthKey = exposedHeaders
  199. .split(',')
  200. .map(x => x.trim())
  201. .concat(authTokenHeaderKey);
  202. } else {
  203. exposedHeadersWithAuthKey = exposedHeaders.concat(authTokenHeaderKey);
  204. }
  205. corsOptions.exposedHeaders = exposedHeadersWithAuthKey;
  206. }
  207. }
  208. }
  209. function logWelcomeMessage(config: RuntimeVendureConfig) {
  210. let version: string;
  211. try {
  212. // eslint-disable-next-line @typescript-eslint/no-var-requires
  213. version = require('../package.json').version;
  214. } catch (e: any) {
  215. version = ' unknown';
  216. }
  217. const { port, shopApiPath, adminApiPath, hostname } = config.apiOptions;
  218. const apiCliGreetings: Array<readonly [string, string]> = [];
  219. const pathToUrl = (path: string) => `http://${hostname || 'localhost'}:${port}/${path}`;
  220. apiCliGreetings.push(['Shop API', pathToUrl(shopApiPath)]);
  221. apiCliGreetings.push(['Admin API', pathToUrl(adminApiPath)]);
  222. apiCliGreetings.push(
  223. ...getPluginStartupMessages().map(({ label, path }) => [label, pathToUrl(path)] as const),
  224. );
  225. const columnarGreetings = arrangeCliGreetingsInColumns(apiCliGreetings);
  226. const title = `Vendure server (v${version}) now running on port ${port}`;
  227. const maxLineLength = Math.max(title.length, ...columnarGreetings.map(l => l.length));
  228. const titlePadLength = title.length < maxLineLength ? Math.floor((maxLineLength - title.length) / 2) : 0;
  229. Logger.info('='.repeat(maxLineLength));
  230. Logger.info(title.padStart(title.length + titlePadLength));
  231. Logger.info('-'.repeat(maxLineLength).padStart(titlePadLength));
  232. columnarGreetings.forEach(line => Logger.info(line));
  233. Logger.info('='.repeat(maxLineLength));
  234. }
  235. function arrangeCliGreetingsInColumns(lines: Array<readonly [string, string]>): string[] {
  236. const columnWidth = Math.max(...lines.map(l => l[0].length)) + 2;
  237. return lines.map(l => `${(l[0] + ':').padEnd(columnWidth)}${l[1]}`);
  238. }
  239. /**
  240. * Fix race condition when modifying DB
  241. * See: https://github.com/vendure-ecommerce/vendure/issues/152
  242. */
  243. function disableSynchronize(userConfig: Readonly<RuntimeVendureConfig>): Readonly<RuntimeVendureConfig> {
  244. const config = {
  245. ...userConfig,
  246. dbConnectionOptions: {
  247. ...userConfig.dbConnectionOptions,
  248. synchronize: false,
  249. } as DataSourceOptions,
  250. };
  251. return config;
  252. }
  253. /**
  254. * Check that the Database tables exist. When running Vendure server & worker
  255. * concurrently for the first time, the worker will attempt to access the
  256. * DB tables before the server has populated them (assuming synchronize = true
  257. * in config). This method will use polling to check the existence of a known table
  258. * before allowing the rest of the worker bootstrap to continue.
  259. * @param worker
  260. */
  261. async function validateDbTablesForWorker(worker: INestApplicationContext) {
  262. const connection: Connection = worker.get(getConnectionToken());
  263. await new Promise<void>(async (resolve, reject) => {
  264. const checkForTables = async (): Promise<boolean> => {
  265. try {
  266. const adminCount = await connection.getRepository(Administrator).count();
  267. return 0 < adminCount;
  268. } catch (e: any) {
  269. return false;
  270. }
  271. };
  272. const pollIntervalMs = 5000;
  273. let attempts = 0;
  274. const maxAttempts = 10;
  275. let validTableStructure = false;
  276. Logger.verbose('Checking for expected DB table structure...');
  277. while (!validTableStructure && attempts < maxAttempts) {
  278. attempts++;
  279. validTableStructure = await checkForTables();
  280. if (validTableStructure) {
  281. Logger.verbose('Table structure verified');
  282. resolve();
  283. return;
  284. }
  285. Logger.verbose(
  286. `Table structure could not be verified, trying again after ${pollIntervalMs}ms (attempt ${attempts} of ${maxAttempts})`,
  287. );
  288. await new Promise(resolve1 => setTimeout(resolve1, pollIntervalMs));
  289. }
  290. reject('Could not validate DB table structure. Aborting bootstrap.');
  291. });
  292. }