@@ -4,7 +4,7 @@ import ProcessorFactory from '../processor/factory';
44import { adjustBackendProxyUrl } from '../lib/elastic'
55import cache from '../lib/cache-instance'
66import { sha3_224 } from 'js-sha3'
7- import AttributeService , { AttributeListParam } from './attribute/service'
7+ import AttributeService from './attribute/service'
88import bodybuilder from 'bodybuilder'
99import { elasticsearch , SearchQuery } from 'storefront-query-builder'
1010
@@ -20,36 +20,6 @@ function _cacheStorageHandler (config, result, hash, tags) {
2020 }
2121}
2222
23- /**
24- * Transforms ES aggregates into valid format for AttributeService - {[attribute_code]: [bucketId1, bucketId2]}
25- * @param body - products response body
26- * @param config - global config
27- * @param indexName - current indexName
28- */
29- async function getProductsAttributesMetadata ( body , config , indexName : string ) : Promise < any > {
30- const attributeListParam : AttributeListParam = Object . keys ( body . aggregations )
31- . filter ( key => body . aggregations [ key ] . buckets . length ) // leave only buckets with values
32- . reduce ( ( acc , key ) => {
33- const attributeCode = key . replace ( / ^ ( a g g _ t e r m s _ | a g g _ r a n g e _ ) | ( _ o p t i o n s ) $ / g, '' )
34- const bucketsIds = body . aggregations [ key ] . buckets . map ( bucket => bucket . key )
35-
36- if ( ! acc [ attributeCode ] ) {
37- acc [ attributeCode ] = [ ]
38- }
39-
40- // there can be more then one attributes for example 'agg_terms_color' and 'agg_terms_color_options'
41- // we need to get buckets from both
42- acc [ attributeCode ] = [ ...new Set ( [ ...acc [ attributeCode ] , ...bucketsIds ] ) ]
43-
44- return acc
45- } , { } )
46-
47- // find attribute list
48- const attributeList : any [ ] = await AttributeService . list ( attributeListParam , config , indexName )
49-
50- return attributeList
51- }
52-
5323function _outputFormatter ( responseBody , format = 'standard' ) {
5424 if ( format === 'compact' ) { // simple formatter
5525 delete responseBody . took
@@ -161,8 +131,10 @@ export default ({config, db}) => async function (req, res, body) {
161131 _resBody . hits . hits = result
162132 _cacheStorageHandler ( config , _resBody , reqHash , tagsArray )
163133 if ( _resBody . aggregations ) {
164- const attributesMetadata = await getProductsAttributesMetadata ( _resBody , config , indexName )
165- _resBody . attribute_metadata = attributesMetadata . map ( AttributeService . transformToMetadata )
134+ const attributeListParam = AttributeService . transformAggsToAttributeListParam ( _resBody . aggregations )
135+ // find attribute list
136+ const attributeList = await AttributeService . list ( attributeListParam , config , indexName )
137+ _resBody . attribute_metadata = attributeList . map ( AttributeService . transformToMetadata )
166138 }
167139 res . json ( _outputFormatter ( _resBody , responseFormat ) ) ;
168140 } ) . catch ( ( err ) => {
0 commit comments