plugin.ts 11 KB

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