plugin.ts 12 KB

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