plugin.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import {
  2. AssetEvent,
  3. CollectionModificationEvent,
  4. DeepRequired,
  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, 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 \@vendure/elasticsearch-plugin`
  39. *
  40. * or
  41. *
  42. * `npm install \@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. schema: () => generateSchemaExtensions(ElasticsearchPlugin.options),
  210. },
  211. workers: [ElasticsearchIndexerController],
  212. })
  213. export class ElasticsearchPlugin implements OnVendureBootstrap {
  214. private static options: DeepRequired<ElasticsearchOptions>;
  215. /** @internal */
  216. constructor(
  217. private eventBus: EventBus,
  218. private elasticsearchService: ElasticsearchService,
  219. private elasticsearchIndexService: ElasticsearchIndexService,
  220. private elasticsearchHealthIndicator: ElasticsearchHealthIndicator,
  221. private healthCheckRegistryService: HealthCheckRegistryService,
  222. ) {}
  223. /**
  224. * Set the plugin options.
  225. */
  226. static init(options: ElasticsearchOptions): Type<ElasticsearchPlugin> {
  227. this.options = mergeWithDefaults(options);
  228. return ElasticsearchPlugin;
  229. }
  230. /** @internal */
  231. async onVendureBootstrap(): Promise<void> {
  232. const { host, port } = ElasticsearchPlugin.options;
  233. try {
  234. const pingResult = await this.elasticsearchService.checkConnection();
  235. } catch (e) {
  236. Logger.error(`Could not connect to Elasticsearch instance at "${host}:${port}"`, loggerCtx);
  237. Logger.error(JSON.stringify(e), loggerCtx);
  238. this.healthCheckRegistryService.registerIndicatorFunction(() =>
  239. this.elasticsearchHealthIndicator.startupCheckFailed(e.message),
  240. );
  241. return;
  242. }
  243. Logger.info(`Sucessfully connected to Elasticsearch instance at "${host}:${port}"`, loggerCtx);
  244. await this.elasticsearchService.createIndicesIfNotExists();
  245. this.elasticsearchIndexService.initJobQueue();
  246. this.healthCheckRegistryService.registerIndicatorFunction(() =>
  247. this.elasticsearchHealthIndicator.isHealthy(),
  248. );
  249. this.eventBus.ofType(ProductEvent).subscribe(event => {
  250. if (event.type === 'deleted') {
  251. return this.elasticsearchIndexService.deleteProduct(event.ctx, event.product);
  252. } else {
  253. return this.elasticsearchIndexService.updateProduct(event.ctx, event.product);
  254. }
  255. });
  256. this.eventBus.ofType(ProductVariantEvent).subscribe(event => {
  257. if (event.type === 'deleted') {
  258. return this.elasticsearchIndexService.deleteVariant(event.ctx, event.variants);
  259. } else {
  260. return this.elasticsearchIndexService.updateVariants(event.ctx, event.variants);
  261. }
  262. });
  263. this.eventBus.ofType(AssetEvent).subscribe(event => {
  264. if (event.type === 'updated') {
  265. return this.elasticsearchIndexService.updateAsset(event.ctx, event.asset);
  266. }
  267. if (event.type === 'deleted') {
  268. return this.elasticsearchIndexService.deleteAsset(event.ctx, event.asset);
  269. }
  270. });
  271. this.eventBus.ofType(ProductChannelEvent).subscribe(event => {
  272. if (event.type === 'assigned') {
  273. return this.elasticsearchIndexService.assignProductToChannel(
  274. event.ctx,
  275. event.product,
  276. event.channelId,
  277. );
  278. } else {
  279. return this.elasticsearchIndexService.removeProductFromChannel(
  280. event.ctx,
  281. event.product,
  282. event.channelId,
  283. );
  284. }
  285. });
  286. const collectionModification$ = this.eventBus.ofType(CollectionModificationEvent);
  287. const closingNotifier$ = collectionModification$.pipe(debounceTime(50));
  288. collectionModification$
  289. .pipe(
  290. buffer(closingNotifier$),
  291. filter(events => 0 < events.length),
  292. map(events => ({
  293. ctx: events[0].ctx,
  294. ids: events.reduce((ids, e) => [...ids, ...e.productVariantIds], [] as ID[]),
  295. })),
  296. filter(e => 0 < e.ids.length),
  297. )
  298. .subscribe(events => {
  299. return this.elasticsearchIndexService.updateVariantsById(events.ctx, events.ids);
  300. });
  301. this.eventBus
  302. .ofType(TaxRateModificationEvent)
  303. // The delay prevents a "TransactionNotStartedError" (in SQLite/sqljs) by allowing any existing
  304. // transactions to complete before a new job is added to the queue (assuming the SQL-based
  305. // JobQueueStrategy).
  306. .pipe(delay(1))
  307. .subscribe(event => {
  308. const defaultTaxZone = event.ctx.channel.defaultTaxZone;
  309. if (defaultTaxZone && idsAreEqual(defaultTaxZone.id, event.taxRate.zone.id)) {
  310. return this.elasticsearchService.updateAll(event.ctx);
  311. }
  312. });
  313. }
  314. }