bootstrap.ts 12 KB

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