plugin.ts 14 KB

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