From 6f595e071b2dd6307f0543c6d8de434620f7ffdd Mon Sep 17 00:00:00 2001 From: Thibault Rey Date: Fri, 18 Oct 2024 14:50:24 +0200 Subject: [PATCH] feat(catalog) : improve category or product page resolution --- services/CatalogService.ts | 49 ++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/services/CatalogService.ts b/services/CatalogService.ts index 569a1b78..adb8bea0 100644 --- a/services/CatalogService.ts +++ b/services/CatalogService.ts @@ -4,7 +4,7 @@ import { BaseServiceElastic } from './BaseServiceElastic' export class CatalogService extends BaseServiceElastic { async search(body: any): Promise { body = { - ...body || {}, + ...(body || {}), collapse: { field: 'url_key', inner_hits: [ @@ -33,20 +33,23 @@ export class CatalogService extends BaseServiceElastic { return { hits, total, aggregations, rawsHits } } - getByURLKey(urlKey: string, sku: string | null): Promise { - const bool: any = { - should: [ - { + /** + * Get product or category by URL key or redirect URL key + */ + getByURLKey(urls: string | string[], sku: string | null): Promise { + urls = Array.isArray(urls) ? urls : [urls] + const bool: any = { should: [] } + let boost = urls?.length + for (const field of ['url_key', 'redirect_url_key']) { + for (const url of urls) { + bool.should.push({ terms: { - url_key: [urlKey] + [field]: [url], + boost } - }, - { - terms: { - redirect_url_key: [urlKey] - } - } - ] + }) + } + boost-- } let query: any = { bool } if (sku) { @@ -68,10 +71,26 @@ export class CatalogService extends BaseServiceElastic { } async getEntityByURLKey(urlKey: string, sku: string | null): Promise { - const result = await this.getByURLKey(urlKey, sku) - return result?.hits?.[0] || null + const urls = [urlKey] + // Clean URL (remove end slash and index.html) to get the right entity + const cleanedURL = this.cleanURL(urlKey) + if (cleanedURL !== urlKey) { + urls.push(cleanedURL) + } + + const result = await this.getByURLKey(urls, sku) + const entity = result?.hits?.[0] || null + if (entity && cleanedURL !== urlKey) { + // Add URL to redirectUrlKey to redirect to the cleaned URL + entity.redirectUrlKey.push(urlKey) + } + return entity } + /** Remove URL end slash and index.html and index.htm page name */ + cleanURL(url: string): string { + return url.replace(/\/(index\.html?|)\/?$/, '') + } find(field: string, value: string[] | number[]): Promise { const terms: any = {} terms[field] = value