plugin.ts 14 KB

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