bootstrap.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. if (config.logger instanceof DefaultLogger) {
  97. config.logger.setDefaultContext('Vendure Worker');
  98. }
  99. Logger.useLogger(config.logger);
  100. Logger.info(`Bootstrapping Vendure Worker (pid: ${process.pid})...`);
  101. setProcessContext('worker');
  102. DefaultLogger.hideNestBoostrapLogs();
  103. const WorkerModule = await import('./worker/worker.module').then(m => m.WorkerModule);
  104. const workerApp = await NestFactory.createApplicationContext(WorkerModule, {
  105. logger: new Logger(),
  106. });
  107. DefaultLogger.restoreOriginalLogLevel();
  108. workerApp.useLogger(new Logger());
  109. workerApp.enableShutdownHooks();
  110. await validateDbTablesForWorker(workerApp);
  111. Logger.info('Vendure Worker is ready');
  112. return new VendureWorker(workerApp);
  113. }
  114. /**
  115. * Setting the global config must be done prior to loading the AppModule.
  116. */
  117. export async function preBootstrapConfig(
  118. userConfig: Partial<VendureConfig>,
  119. ): Promise<Readonly<RuntimeVendureConfig>> {
  120. if (userConfig) {
  121. setConfig(userConfig);
  122. }
  123. const entities = await getAllEntities(userConfig);
  124. const { coreSubscribersMap } = await import('./entity/subscribers');
  125. setConfig({
  126. dbConnectionOptions: {
  127. entities,
  128. subscribers: [
  129. ...(userConfig.dbConnectionOptions?.subscribers ?? []),
  130. ...(Object.values(coreSubscribersMap) as Array<Type<EntitySubscriberInterface>>),
  131. ],
  132. },
  133. });
  134. let config = getConfig();
  135. const entityIdStrategy = config.entityOptions.entityIdStrategy ?? config.entityIdStrategy;
  136. setEntityIdStrategy(entityIdStrategy, entities);
  137. const customFieldValidationResult = validateCustomFieldsConfig(config.customFields, entities);
  138. if (!customFieldValidationResult.valid) {
  139. process.exitCode = 1;
  140. throw new Error(`CustomFields config error:\n- ` + customFieldValidationResult.errors.join('\n- '));
  141. }
  142. config = await runPluginConfigurations(config);
  143. registerCustomEntityFields(config);
  144. await runEntityMetadataModifiers(config);
  145. setExposedHeaders(config);
  146. return config;
  147. }
  148. /**
  149. * Initialize any configured plugins.
  150. */
  151. async function runPluginConfigurations(config: RuntimeVendureConfig): Promise<RuntimeVendureConfig> {
  152. for (const plugin of config.plugins) {
  153. const configFn = getConfigurationFunction(plugin);
  154. if (typeof configFn === 'function') {
  155. config = await configFn(config);
  156. }
  157. }
  158. return config;
  159. }
  160. /**
  161. * Returns an array of core entities and any additional entities defined in plugins.
  162. */
  163. export async function getAllEntities(userConfig: Partial<VendureConfig>): Promise<Array<Type<any>>> {
  164. const coreEntities = Object.values(coreEntitiesMap) as Array<Type<any>>;
  165. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  166. const allEntities: Array<Type<any>> = coreEntities;
  167. // Check to ensure that no plugins are defining entities with names
  168. // which conflict with existing entities.
  169. for (const pluginEntity of pluginEntities) {
  170. if (allEntities.find(e => e.name === pluginEntity.name)) {
  171. throw new InternalServerError(`error.entity-name-conflict`, { entityName: pluginEntity.name });
  172. } else {
  173. allEntities.push(pluginEntity);
  174. }
  175. }
  176. return allEntities;
  177. }
  178. /**
  179. * If the 'bearer' tokenMethod is being used, then we automatically expose the authTokenHeaderKey header
  180. * in the CORS options, making sure to preserve any user-configured exposedHeaders.
  181. */
  182. function setExposedHeaders(config: Readonly<RuntimeVendureConfig>) {
  183. const { tokenMethod } = config.authOptions;
  184. const isUsingBearerToken =
  185. tokenMethod === 'bearer' || (Array.isArray(tokenMethod) && tokenMethod.includes('bearer'));
  186. if (isUsingBearerToken) {
  187. const authTokenHeaderKey = config.authOptions.authTokenHeaderKey;
  188. const corsOptions = config.apiOptions.cors;
  189. if (typeof corsOptions !== 'boolean') {
  190. const { exposedHeaders } = corsOptions;
  191. let exposedHeadersWithAuthKey: string[];
  192. if (!exposedHeaders) {
  193. exposedHeadersWithAuthKey = [authTokenHeaderKey];
  194. } else if (typeof exposedHeaders === 'string') {
  195. exposedHeadersWithAuthKey = exposedHeaders
  196. .split(',')
  197. .map(x => x.trim())
  198. .concat(authTokenHeaderKey);
  199. } else {
  200. exposedHeadersWithAuthKey = exposedHeaders.concat(authTokenHeaderKey);
  201. }
  202. corsOptions.exposedHeaders = exposedHeadersWithAuthKey;
  203. }
  204. }
  205. }
  206. function logWelcomeMessage(config: RuntimeVendureConfig) {
  207. let version: string;
  208. try {
  209. version = require('../package.json').version;
  210. } catch (e) {
  211. version = ' unknown';
  212. }
  213. const { port, shopApiPath, adminApiPath, hostname } = config.apiOptions;
  214. const apiCliGreetings: Array<readonly [string, string]> = [];
  215. const pathToUrl = (path: string) => `http://${hostname || 'localhost'}:${port}/${path}`;
  216. apiCliGreetings.push(['Shop API', pathToUrl(shopApiPath)]);
  217. apiCliGreetings.push(['Admin API', pathToUrl(adminApiPath)]);
  218. apiCliGreetings.push(
  219. ...getPluginStartupMessages().map(({ label, path }) => [label, pathToUrl(path)] as const),
  220. );
  221. const columnarGreetings = arrangeCliGreetingsInColumns(apiCliGreetings);
  222. const title = `Vendure server (v${version}) now running on port ${port}`;
  223. const maxLineLength = Math.max(title.length, ...columnarGreetings.map(l => l.length));
  224. const titlePadLength = title.length < maxLineLength ? Math.floor((maxLineLength - title.length) / 2) : 0;
  225. Logger.info(`=`.repeat(maxLineLength));
  226. Logger.info(title.padStart(title.length + titlePadLength));
  227. Logger.info('-'.repeat(maxLineLength).padStart(titlePadLength));
  228. columnarGreetings.forEach(line => Logger.info(line));
  229. Logger.info(`=`.repeat(maxLineLength));
  230. }
  231. function arrangeCliGreetingsInColumns(lines: Array<readonly [string, string]>): string[] {
  232. const columnWidth = Math.max(...lines.map(l => l[0].length)) + 2;
  233. return lines.map(l => `${(l[0] + ':').padEnd(columnWidth)}${l[1]}`);
  234. }
  235. /**
  236. * Fix race condition when modifying DB
  237. * See: https://github.com/vendure-ecommerce/vendure/issues/152
  238. */
  239. function disableSynchronize(userConfig: Readonly<RuntimeVendureConfig>): Readonly<RuntimeVendureConfig> {
  240. const config = { ...userConfig };
  241. config.dbConnectionOptions = {
  242. ...userConfig.dbConnectionOptions,
  243. synchronize: false,
  244. } as ConnectionOptions;
  245. return config;
  246. }
  247. /**
  248. * Check that the Database tables exist. When running Vendure server & worker
  249. * concurrently for the first time, the worker will attempt to access the
  250. * DB tables before the server has populated them (assuming synchronize = true
  251. * in config). This method will use polling to check the existence of a known table
  252. * before allowing the rest of the worker bootstrap to continue.
  253. * @param worker
  254. */
  255. async function validateDbTablesForWorker(worker: INestApplicationContext) {
  256. const connection: Connection = worker.get(getConnectionToken());
  257. await new Promise<void>(async (resolve, reject) => {
  258. const checkForTables = async (): Promise<boolean> => {
  259. try {
  260. const adminCount = await connection.getRepository(Administrator).count();
  261. return 0 < adminCount;
  262. } catch (e) {
  263. return false;
  264. }
  265. };
  266. const pollIntervalMs = 5000;
  267. let attempts = 0;
  268. const maxAttempts = 10;
  269. let validTableStructure = false;
  270. Logger.verbose('Checking for expected DB table structure...');
  271. while (!validTableStructure && attempts < maxAttempts) {
  272. attempts++;
  273. validTableStructure = await checkForTables();
  274. if (validTableStructure) {
  275. Logger.verbose('Table structure verified');
  276. resolve();
  277. return;
  278. }
  279. Logger.verbose(
  280. `Table structure could not be verified, trying again after ${pollIntervalMs}ms (attempt ${attempts} of ${maxAttempts})`,
  281. );
  282. await new Promise(resolve1 => setTimeout(resolve1, pollIntervalMs));
  283. }
  284. reject(`Could not validate DB table structure. Aborting bootstrap.`);
  285. });
  286. }