bootstrap.ts 12 KB

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