bootstrap.ts 12 KB

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