plugin.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import { NodeOptions } from '@elastic/elasticsearch';
  2. import { OnApplicationBootstrap } from '@nestjs/common';
  3. import {
  4. AssetEvent,
  5. BUFFER_SEARCH_INDEX_UPDATES,
  6. CollectionModificationEvent,
  7. EventBus,
  8. HealthCheckRegistryService,
  9. ID,
  10. idsAreEqual,
  11. Logger,
  12. PluginCommonModule,
  13. ProductChannelEvent,
  14. ProductEvent,
  15. ProductVariantChannelEvent,
  16. ProductVariantEvent,
  17. SearchJobBufferService,
  18. StockMovementEvent,
  19. TaxRateModificationEvent,
  20. Type,
  21. VendurePlugin,
  22. } from '@vendure/core';
  23. import { buffer, debounceTime, delay, filter, map } from 'rxjs/operators';
  24. import { generateSchemaExtensions } from './api/api-extensions';
  25. import { CustomMappingsResolver } from './api/custom-mappings.resolver';
  26. import { CustomScriptFieldsResolver } from './api/custom-script-fields.resolver';
  27. import {
  28. AdminElasticSearchResolver,
  29. EntityElasticSearchResolver,
  30. ShopElasticSearchResolver,
  31. } from './api/elasticsearch-resolver';
  32. import { ELASTIC_SEARCH_OPTIONS, loggerCtx } from './constants';
  33. import { ElasticsearchHealthIndicator } from './elasticsearch.health';
  34. import { ElasticsearchService } from './elasticsearch.service';
  35. import { ElasticsearchIndexService } from './indexing/elasticsearch-index.service';
  36. import { ElasticsearchIndexerController } from './indexing/indexer.controller';
  37. import { ElasticsearchOptions, ElasticsearchRuntimeOptions, mergeWithDefaults } from './options';
  38. function getCustomResolvers(options: ElasticsearchRuntimeOptions) {
  39. const requiresUnionResolver =
  40. 0 < Object.keys(options.customProductMappings || {}).length &&
  41. 0 < Object.keys(options.customProductVariantMappings || {}).length;
  42. const requiresUnionScriptResolver =
  43. 0 <
  44. Object.values(options.searchConfig.scriptFields || {}).filter(
  45. field => field.context !== 'product',
  46. ).length &&
  47. 0 <
  48. Object.values(options.searchConfig.scriptFields || {}).filter(
  49. field => field.context !== 'variant',
  50. ).length;
  51. return [
  52. ...(requiresUnionResolver ? [CustomMappingsResolver] : []),
  53. ...(requiresUnionScriptResolver ? [CustomScriptFieldsResolver] : []),
  54. ];
  55. }
  56. /**
  57. * @description
  58. * This plugin allows your product search to be powered by [Elasticsearch](https://github.com/elastic/elasticsearch) - a powerful Open Source search
  59. * engine. This is a drop-in replacement for the DefaultSearchPlugin which exposes many powerful configuration options enabling your storefront
  60. * to support a wide range of use-cases such as indexing of custom properties, fine control over search index configuration, and to leverage
  61. * advanced Elasticsearch features like spacial search.
  62. *
  63. * ## Installation
  64. *
  65. * **Requires Elasticsearch v7.0 < required Elasticsearch version < 7.10 **
  66. * Elasticsearch version 7.10.2 will throw error due to incompatibility with elasticsearch-js client.
  67. * [Check here for more info](https://github.com/elastic/elasticsearch-js/issues/1519).
  68. *
  69. * `yarn add \@elastic/elasticsearch \@vendure/elasticsearch-plugin`
  70. *
  71. * or
  72. *
  73. * `npm install \@elastic/elasticsearch \@vendure/elasticsearch-plugin`
  74. *
  75. * Make sure to remove the `DefaultSearchPlugin` if it is still in the VendureConfig plugins array.
  76. *
  77. * Then add the `ElasticsearchPlugin`, calling the `.init()` method with {@link ElasticsearchOptions}:
  78. *
  79. * @example
  80. * ```ts
  81. * import { ElasticsearchPlugin } from '\@vendure/elasticsearch-plugin';
  82. *
  83. * const config: VendureConfig = {
  84. * // Add an instance of the plugin to the plugins array
  85. * plugins: [
  86. * ElasticsearchPlugin.init({
  87. * host: 'http://localhost',
  88. * port: 9200,
  89. * }),
  90. * ],
  91. * };
  92. * ```
  93. *
  94. * ## Search API Extensions
  95. * This plugin extends the default search query of the Shop API, allowing richer querying of your product data.
  96. *
  97. * The [SearchResponse](/reference/graphql-api/shop/object-types/#searchresponse) type is extended with information
  98. * about price ranges in the result set:
  99. * ```graphql
  100. * extend type SearchResponse {
  101. * prices: SearchResponsePriceData!
  102. * }
  103. *
  104. * type SearchResponsePriceData {
  105. * range: PriceRange!
  106. * rangeWithTax: PriceRange!
  107. * buckets: [PriceRangeBucket!]!
  108. * bucketsWithTax: [PriceRangeBucket!]!
  109. * }
  110. *
  111. * type PriceRangeBucket {
  112. * to: Int!
  113. * count: Int!
  114. * }
  115. *
  116. * extend input SearchInput {
  117. * priceRange: PriceRangeInput
  118. * priceRangeWithTax: PriceRangeInput
  119. * inStock: Boolean
  120. * }
  121. *
  122. * input PriceRangeInput {
  123. * min: Int!
  124. * max: Int!
  125. * }
  126. * ```
  127. *
  128. * This `SearchResponsePriceData` type allows you to query data about the range of prices in the result set.
  129. *
  130. * ## Example Request & Response
  131. *
  132. * ```graphql
  133. * {
  134. * search (input: {
  135. * term: "table easel"
  136. * groupByProduct: true
  137. * priceRange: {
  138. min: 500
  139. max: 7000
  140. }
  141. * }) {
  142. * totalItems
  143. * prices {
  144. * range {
  145. * min
  146. * max
  147. * }
  148. * buckets {
  149. * to
  150. * count
  151. * }
  152. * }
  153. * items {
  154. * productName
  155. * score
  156. * price {
  157. * ...on PriceRange {
  158. * min
  159. * max
  160. * }
  161. * }
  162. * }
  163. * }
  164. * }
  165. * ```
  166. *
  167. * ```json
  168. *{
  169. * "data": {
  170. * "search": {
  171. * "totalItems": 9,
  172. * "prices": {
  173. * "range": {
  174. * "min": 999,
  175. * "max": 6396,
  176. * },
  177. * "buckets": [
  178. * {
  179. * "to": 1000,
  180. * "count": 1
  181. * },
  182. * {
  183. * "to": 2000,
  184. * "count": 2
  185. * },
  186. * {
  187. * "to": 3000,
  188. * "count": 3
  189. * },
  190. * {
  191. * "to": 4000,
  192. * "count": 1
  193. * },
  194. * {
  195. * "to": 5000,
  196. * "count": 1
  197. * },
  198. * {
  199. * "to": 7000,
  200. * "count": 1
  201. * }
  202. * ]
  203. * },
  204. * "items": [
  205. * {
  206. * "productName": "Loxley Yorkshire Table Easel",
  207. * "score": 30.58831,
  208. * "price": {
  209. * "min": 4984,
  210. * "max": 4984
  211. * }
  212. * },
  213. * // ... truncated
  214. * ]
  215. * }
  216. * }
  217. *}
  218. * ```
  219. *
  220. * @docsCategory core plugins/ElasticsearchPlugin
  221. */
  222. @VendurePlugin({
  223. imports: [PluginCommonModule],
  224. providers: [
  225. ElasticsearchIndexService,
  226. ElasticsearchService,
  227. ElasticsearchHealthIndicator,
  228. ElasticsearchIndexerController,
  229. SearchJobBufferService,
  230. { provide: ELASTIC_SEARCH_OPTIONS, useFactory: () => ElasticsearchPlugin.options },
  231. {
  232. provide: BUFFER_SEARCH_INDEX_UPDATES,
  233. useFactory: () => ElasticsearchPlugin.options.bufferUpdates === true,
  234. },
  235. ],
  236. adminApiExtensions: {
  237. resolvers: () => [
  238. AdminElasticSearchResolver,
  239. EntityElasticSearchResolver,
  240. ...getCustomResolvers(ElasticsearchPlugin.options),
  241. ],
  242. schema: () => generateSchemaExtensions(ElasticsearchPlugin.options as any),
  243. },
  244. shopApiExtensions: {
  245. resolvers: () => [
  246. ShopElasticSearchResolver,
  247. EntityElasticSearchResolver,
  248. ...getCustomResolvers(ElasticsearchPlugin.options),
  249. ],
  250. // `any` cast is there due to a strange error "Property '[Symbol.iterator]' is missing in type... URLSearchParams"
  251. // which looks like possibly a TS/definitions bug.
  252. schema: () => generateSchemaExtensions(ElasticsearchPlugin.options as any),
  253. },
  254. compatibility: '^3.0.0',
  255. })
  256. export class ElasticsearchPlugin implements OnApplicationBootstrap {
  257. private static options: ElasticsearchRuntimeOptions;
  258. /** @internal */
  259. constructor(
  260. private eventBus: EventBus,
  261. private elasticsearchService: ElasticsearchService,
  262. private elasticsearchIndexService: ElasticsearchIndexService,
  263. private elasticsearchHealthIndicator: ElasticsearchHealthIndicator,
  264. private healthCheckRegistryService: HealthCheckRegistryService,
  265. ) {}
  266. /**
  267. * Set the plugin options.
  268. */
  269. static init(options: ElasticsearchOptions): Type<ElasticsearchPlugin> {
  270. this.options = mergeWithDefaults(options);
  271. return ElasticsearchPlugin;
  272. }
  273. /** @internal */
  274. async onApplicationBootstrap(): Promise<void> {
  275. const nodeName = this.nodeName();
  276. try {
  277. await this.elasticsearchService.checkConnection();
  278. } catch (e: any) {
  279. Logger.error(`Could not connect to Elasticsearch instance at "${nodeName}"`, loggerCtx);
  280. Logger.error(JSON.stringify(e), loggerCtx);
  281. this.healthCheckRegistryService.registerIndicatorFunction(() =>
  282. this.elasticsearchHealthIndicator.startupCheckFailed(e.message),
  283. );
  284. return;
  285. }
  286. Logger.info(`Successfully connected to Elasticsearch instance at "${nodeName}"`, loggerCtx);
  287. await this.elasticsearchService.createIndicesIfNotExists();
  288. this.healthCheckRegistryService.registerIndicatorFunction(() =>
  289. this.elasticsearchHealthIndicator.isHealthy(),
  290. );
  291. this.eventBus.ofType(ProductEvent).subscribe(event => {
  292. if (event.type === 'deleted') {
  293. return this.elasticsearchIndexService.deleteProduct(event.ctx, event.product);
  294. } else {
  295. return this.elasticsearchIndexService.updateProduct(event.ctx, event.product);
  296. }
  297. });
  298. this.eventBus.ofType(ProductVariantEvent).subscribe(event => {
  299. if (event.type === 'deleted') {
  300. return this.elasticsearchIndexService.deleteVariant(event.ctx, event.variants);
  301. } else {
  302. return this.elasticsearchIndexService.updateVariants(event.ctx, event.variants);
  303. }
  304. });
  305. this.eventBus.ofType(AssetEvent).subscribe(event => {
  306. if (event.type === 'updated') {
  307. return this.elasticsearchIndexService.updateAsset(event.ctx, event.asset);
  308. }
  309. if (event.type === 'deleted') {
  310. return this.elasticsearchIndexService.deleteAsset(event.ctx, event.asset);
  311. }
  312. });
  313. this.eventBus.ofType(ProductChannelEvent).subscribe(event => {
  314. if (event.type === 'assigned') {
  315. return this.elasticsearchIndexService.assignProductToChannel(
  316. event.ctx,
  317. event.product,
  318. event.channelId,
  319. );
  320. } else {
  321. return this.elasticsearchIndexService.removeProductFromChannel(
  322. event.ctx,
  323. event.product,
  324. event.channelId,
  325. );
  326. }
  327. });
  328. this.eventBus.ofType(ProductVariantChannelEvent).subscribe(event => {
  329. if (event.type === 'assigned') {
  330. return this.elasticsearchIndexService.assignVariantToChannel(
  331. event.ctx,
  332. event.productVariant.id,
  333. event.channelId,
  334. );
  335. } else {
  336. return this.elasticsearchIndexService.removeVariantFromChannel(
  337. event.ctx,
  338. event.productVariant.id,
  339. event.channelId,
  340. );
  341. }
  342. });
  343. this.eventBus.ofType(StockMovementEvent).subscribe(event => {
  344. return this.elasticsearchIndexService.updateVariants(
  345. event.ctx,
  346. event.stockMovements.map(m => m.productVariant),
  347. );
  348. });
  349. // TODO: Remove this buffering logic because because we have dedicated buffering based on #1137
  350. const collectionModification$ = this.eventBus.ofType(CollectionModificationEvent);
  351. const closingNotifier$ = collectionModification$.pipe(debounceTime(50));
  352. collectionModification$
  353. .pipe(
  354. buffer(closingNotifier$),
  355. filter(events => 0 < events.length),
  356. map(events => ({
  357. ctx: events[0].ctx,
  358. ids: events.reduce((ids, e) => [...ids, ...e.productVariantIds], [] as ID[]),
  359. })),
  360. filter(e => 0 < e.ids.length),
  361. )
  362. .subscribe(events => {
  363. return this.elasticsearchIndexService.updateVariantsById(events.ctx, events.ids);
  364. });
  365. this.eventBus
  366. .ofType(TaxRateModificationEvent)
  367. // The delay prevents a "TransactionNotStartedError" (in SQLite/sqljs) by allowing any existing
  368. // transactions to complete before a new job is added to the queue (assuming the SQL-based
  369. // JobQueueStrategy).
  370. // TODO: should be able to remove owing to f0fd6625
  371. .pipe(delay(1))
  372. .subscribe(event => {
  373. const defaultTaxZone = event.ctx.channel.defaultTaxZone;
  374. if (defaultTaxZone && idsAreEqual(defaultTaxZone.id, event.taxRate.zone.id)) {
  375. return this.elasticsearchService.reindex(event.ctx);
  376. }
  377. });
  378. }
  379. /**
  380. * Returns a string representation of the target node(s) that the Elasticsearch
  381. * client is configured to connect to.
  382. */
  383. private nodeName(): string {
  384. const { host, port, clientOptions } = ElasticsearchPlugin.options;
  385. const node = clientOptions?.node;
  386. const nodes = clientOptions?.nodes;
  387. if (nodes) {
  388. return [...(Array.isArray(nodes) ? nodes : [nodes])].join(', ');
  389. }
  390. if (node) {
  391. if (Array.isArray(node)) {
  392. return (node as any[])
  393. .map((n: string | NodeOptions) => {
  394. return typeof n === 'string' ? n : n.url.toString();
  395. })
  396. .join(', ');
  397. } else {
  398. return typeof node === 'string' ? node : node.url.toString();
  399. }
  400. }
  401. return `${host}:${port}`;
  402. }
  403. }