plugin.ts 13 KB

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