diff --git a/src/plugins/data/common/search/aggs/agg_configs.test.ts b/src/plugins/data/common/search/aggs/agg_configs.test.ts index 076fbd9de3d7..583c73a2724a 100644 --- a/src/plugins/data/common/search/aggs/agg_configs.test.ts +++ b/src/plugins/data/common/search/aggs/agg_configs.test.ts @@ -117,7 +117,7 @@ describe('AggConfigs', () => { expect(ac.aggs).toHaveLength(3); }); - it('adds new AggConfig entries to AggConfigs by default', () => { + it('adds new AggConfig entries to end of AggConfigs by default', () => { const configStates = [ { enabled: true, @@ -136,6 +136,7 @@ describe('AggConfigs', () => { schema: 'split', }); expect(ac.aggs).toHaveLength(2); + expect(ac.aggs[1].schema).toBe('split'); }); it('does not add an agg to AggConfigs if addToAggConfigs: false', () => { @@ -161,6 +162,55 @@ describe('AggConfigs', () => { ); expect(ac.aggs).toHaveLength(1); }); + + it('adds new AggConfig entries to beginning of AggConfigs if mustBeFirst: true', () => { + const configStates = [ + { + enabled: true, + type: 'histogram', + params: {}, + }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + expect(ac.aggs).toHaveLength(1); + + ac.createAggConfig( + { + enabled: true, + type: 'terms', + params: {}, + schema: 'split', + }, + { mustBeFirst: true } + ); + expect(ac.aggs).toHaveLength(2); + expect(ac.aggs[0].schema).toBe('split'); + }); + + it('does not add an agg to AggConfigs if addToAggConfigs: false and mustBeFirst: true', () => { + const configStates = [ + { + enabled: true, + type: 'histogram', + params: {}, + }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + expect(ac.aggs).toHaveLength(1); + + ac.createAggConfig( + { + enabled: true, + type: 'terms', + params: {}, + schema: 'split', + }, + { addToAggConfigs: false, mustBeFirst: true } + ); + expect(ac.aggs).toHaveLength(1); + }); }); describe('#getRequestAggs', () => { diff --git a/src/plugins/data/common/search/aggs/agg_configs.ts b/src/plugins/data/common/search/aggs/agg_configs.ts index 90ad5820ea3c..8f13fcd54f0e 100644 --- a/src/plugins/data/common/search/aggs/agg_configs.ts +++ b/src/plugins/data/common/search/aggs/agg_configs.ts @@ -130,10 +130,10 @@ export class AggConfigs { createAggConfig = ( params: CreateAggConfigParams, - { addToAggConfigs = true } = {} + { addToAggConfigs = true, mustBeFirst = false } = {} ) => { const { type } = params; - let aggConfig; + let aggConfig: AggConfig; if (params instanceof AggConfig) { aggConfig = params; @@ -145,8 +145,12 @@ export class AggConfigs { }); } + const addAggConfig = () => { + return mustBeFirst ? this.aggs.unshift(aggConfig) : this.aggs.push(aggConfig); + }; + if (addToAggConfigs) { - this.aggs.push(aggConfig); + addAggConfig(); } return aggConfig as T;