bootstrap.ts 12 KB

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