bootstrap.ts 14 KB

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