bootstrap.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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]({{< relref "vendure-worker" >}}).
  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. const entityIdStrategy = config.entityOptions.entityIdStrategy ?? config.entityIdStrategy;
  141. setEntityIdStrategy(entityIdStrategy, entities);
  142. const moneyStrategy = config.entityOptions.moneyStrategy;
  143. setMoneyStrategy(moneyStrategy, entities);
  144. const customFieldValidationResult = validateCustomFieldsConfig(config.customFields, entities);
  145. if (!customFieldValidationResult.valid) {
  146. process.exitCode = 1;
  147. throw new Error('CustomFields config error:\n- ' + customFieldValidationResult.errors.join('\n- '));
  148. }
  149. config = await runPluginConfigurations(config);
  150. registerCustomEntityFields(config);
  151. await runEntityMetadataModifiers(config);
  152. setExposedHeaders(config);
  153. return config;
  154. }
  155. function checkPluginCompatibility(config: RuntimeVendureConfig): void {
  156. for (const plugin of config.plugins) {
  157. const compatibility = getCompatibility(plugin);
  158. const pluginName = (plugin as any).name as string;
  159. if (!compatibility) {
  160. Logger.info(
  161. `The plugin "${pluginName}" does not specify a compatibility range, so it is not guaranteed to be compatible with this version of Vendure.`,
  162. );
  163. } else {
  164. if (!satisfies(VENDURE_VERSION, compatibility, { loose: true, includePrerelease: true })) {
  165. Logger.error(
  166. `Plugin "${pluginName}" is not compatible with this version of Vendure. ` +
  167. `It specifies a semver range of "${compatibility}" but the current version is "${VENDURE_VERSION}".`,
  168. );
  169. throw new InternalServerError(
  170. `Plugin "${pluginName}" is not compatible with this version of Vendure.`,
  171. );
  172. }
  173. }
  174. }
  175. }
  176. /**
  177. * Initialize any configured plugins.
  178. */
  179. async function runPluginConfigurations(config: RuntimeVendureConfig): Promise<RuntimeVendureConfig> {
  180. for (const plugin of config.plugins) {
  181. const configFn = getConfigurationFunction(plugin);
  182. if (typeof configFn === 'function') {
  183. config = await configFn(config);
  184. }
  185. }
  186. return config;
  187. }
  188. /**
  189. * Returns an array of core entities and any additional entities defined in plugins.
  190. */
  191. export async function getAllEntities(userConfig: Partial<VendureConfig>): Promise<Array<Type<any>>> {
  192. const coreEntities = Object.values(coreEntitiesMap) as Array<Type<any>>;
  193. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  194. const allEntities: Array<Type<any>> = coreEntities;
  195. // Check to ensure that no plugins are defining entities with names
  196. // which conflict with existing entities.
  197. for (const pluginEntity of pluginEntities) {
  198. if (allEntities.find(e => e.name === pluginEntity.name)) {
  199. throw new InternalServerError('error.entity-name-conflict', { entityName: pluginEntity.name });
  200. } else {
  201. allEntities.push(pluginEntity);
  202. }
  203. }
  204. return allEntities;
  205. }
  206. /**
  207. * If the 'bearer' tokenMethod is being used, then we automatically expose the authTokenHeaderKey header
  208. * in the CORS options, making sure to preserve any user-configured exposedHeaders.
  209. */
  210. function setExposedHeaders(config: Readonly<RuntimeVendureConfig>) {
  211. const { tokenMethod } = config.authOptions;
  212. const isUsingBearerToken =
  213. tokenMethod === 'bearer' || (Array.isArray(tokenMethod) && tokenMethod.includes('bearer'));
  214. if (isUsingBearerToken) {
  215. const authTokenHeaderKey = config.authOptions.authTokenHeaderKey;
  216. const corsOptions = config.apiOptions.cors;
  217. if (typeof corsOptions !== 'boolean') {
  218. const { exposedHeaders } = corsOptions;
  219. let exposedHeadersWithAuthKey: string[];
  220. if (!exposedHeaders) {
  221. exposedHeadersWithAuthKey = [authTokenHeaderKey];
  222. } else if (typeof exposedHeaders === 'string') {
  223. exposedHeadersWithAuthKey = exposedHeaders
  224. .split(',')
  225. .map(x => x.trim())
  226. .concat(authTokenHeaderKey);
  227. } else {
  228. exposedHeadersWithAuthKey = exposedHeaders.concat(authTokenHeaderKey);
  229. }
  230. corsOptions.exposedHeaders = exposedHeadersWithAuthKey;
  231. }
  232. }
  233. }
  234. function logWelcomeMessage(config: RuntimeVendureConfig) {
  235. const { port, shopApiPath, adminApiPath, hostname } = config.apiOptions;
  236. const apiCliGreetings: Array<readonly [string, string]> = [];
  237. const pathToUrl = (path: string) => `http://${hostname || 'localhost'}:${port}/${path}`;
  238. apiCliGreetings.push(['Shop API', pathToUrl(shopApiPath)]);
  239. apiCliGreetings.push(['Admin API', pathToUrl(adminApiPath)]);
  240. apiCliGreetings.push(
  241. ...getPluginStartupMessages().map(({ label, path }) => [label, pathToUrl(path)] as const),
  242. );
  243. const columnarGreetings = arrangeCliGreetingsInColumns(apiCliGreetings);
  244. const title = `Vendure server (v${VENDURE_VERSION}) now running on port ${port}`;
  245. const maxLineLength = Math.max(title.length, ...columnarGreetings.map(l => l.length));
  246. const titlePadLength = title.length < maxLineLength ? Math.floor((maxLineLength - title.length) / 2) : 0;
  247. Logger.info('='.repeat(maxLineLength));
  248. Logger.info(title.padStart(title.length + titlePadLength));
  249. Logger.info('-'.repeat(maxLineLength).padStart(titlePadLength));
  250. columnarGreetings.forEach(line => Logger.info(line));
  251. Logger.info('='.repeat(maxLineLength));
  252. }
  253. function arrangeCliGreetingsInColumns(lines: Array<readonly [string, string]>): string[] {
  254. const columnWidth = Math.max(...lines.map(l => l[0].length)) + 2;
  255. return lines.map(l => `${(l[0] + ':').padEnd(columnWidth)}${l[1]}`);
  256. }
  257. /**
  258. * Fix race condition when modifying DB
  259. * See: https://github.com/vendure-ecommerce/vendure/issues/152
  260. */
  261. function disableSynchronize(userConfig: Readonly<RuntimeVendureConfig>): Readonly<RuntimeVendureConfig> {
  262. const config = {
  263. ...userConfig,
  264. dbConnectionOptions: {
  265. ...userConfig.dbConnectionOptions,
  266. synchronize: false,
  267. } as DataSourceOptions,
  268. };
  269. return config;
  270. }
  271. /**
  272. * Check that the Database tables exist. When running Vendure server & worker
  273. * concurrently for the first time, the worker will attempt to access the
  274. * DB tables before the server has populated them (assuming synchronize = true
  275. * in config). This method will use polling to check the existence of a known table
  276. * before allowing the rest of the worker bootstrap to continue.
  277. * @param worker
  278. */
  279. async function validateDbTablesForWorker(worker: INestApplicationContext) {
  280. const connection: Connection = worker.get(getConnectionToken());
  281. await new Promise<void>(async (resolve, reject) => {
  282. const checkForTables = async (): Promise<boolean> => {
  283. try {
  284. const adminCount = await connection.getRepository(Administrator).count();
  285. return 0 < adminCount;
  286. } catch (e: any) {
  287. return false;
  288. }
  289. };
  290. const pollIntervalMs = 5000;
  291. let attempts = 0;
  292. const maxAttempts = 10;
  293. let validTableStructure = false;
  294. Logger.verbose('Checking for expected DB table structure...');
  295. while (!validTableStructure && attempts < maxAttempts) {
  296. attempts++;
  297. validTableStructure = await checkForTables();
  298. if (validTableStructure) {
  299. Logger.verbose('Table structure verified');
  300. resolve();
  301. return;
  302. }
  303. Logger.verbose(
  304. `Table structure could not be verified, trying again after ${pollIntervalMs}ms (attempt ${attempts} of ${maxAttempts})`,
  305. );
  306. await new Promise(resolve1 => setTimeout(resolve1, pollIntervalMs));
  307. }
  308. reject('Could not validate DB table structure. Aborting bootstrap.');
  309. });
  310. }