plugin.ts 13 KB

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