Skip to content

Commit

Permalink
[data.search.aggs] Throw an error when trying to create an agg type t…
Browse files Browse the repository at this point in the history
…hat doesn't exist. (#81509)
  • Loading branch information
lukeelmers committed Nov 10, 2020
1 parent 7a67cff commit f193d9c
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 12 deletions.
10 changes: 0 additions & 10 deletions src/plugins/data/common/search/aggs/agg_config.test.ts
Expand Up @@ -680,16 +680,6 @@ describe('AggConfig', () => {
const json = aggConfig.toExpressionAst()?.arguments.json;
expect(json).toEqual([JSON.stringify(configStates.params.json)]);
});

it(`returns undefined if an expressionName doesn't exist on the agg type`, () => {
const ac = new AggConfigs(indexPattern, [], { typesRegistry });
const configStates = {
type: 'unknown type',
params: {},
};
const aggConfig = ac.createAggConfig(configStates);
expect(aggConfig.toExpressionAst()).toBe(undefined);
});
});

describe('#makeLabel', () => {
Expand Down
21 changes: 21 additions & 0 deletions src/plugins/data/common/search/aggs/agg_configs.test.ts
Expand Up @@ -150,6 +150,27 @@ describe('AggConfigs', () => {
);
expect(ac.aggs).toHaveLength(1);
});

it(`throws if trying to add an agg which doesn't have a type in the registry`, () => {
const configStates = [
{
enabled: true,
type: 'histogram',
params: {},
},
];

const ac = new AggConfigs(indexPattern, configStates, { typesRegistry });
expect(() =>
ac.createAggConfig({
enabled: true,
type: 'oops',
params: {},
})
).toThrowErrorMatchingInlineSnapshot(
`"Unable to find a registered agg type for \\"oops\\"."`
);
});
});

describe('#getRequestAggs', () => {
Expand Down
19 changes: 17 additions & 2 deletions src/plugins/data/common/search/aggs/agg_configs.ts
Expand Up @@ -18,6 +18,7 @@
*/

import _ from 'lodash';
import { i18n } from '@kbn/i18n';
import { Assign } from '@kbn/utility-types';

import { ISearchOptions, ISearchSource } from 'src/plugins/data/public';
Expand Down Expand Up @@ -122,15 +123,29 @@ export class AggConfigs {
{ addToAggConfigs = true } = {}
) => {
const { type } = params;
let aggConfig;
const getType = (t: string) => {
const typeFromRegistry = this.typesRegistry.get(t);

if (!typeFromRegistry) {
throw new Error(
i18n.translate('data.search.aggs.error.aggNotFound', {
defaultMessage: 'Unable to find a registered agg type for "{type}".',
values: { type: type as string },
})
);
}

return typeFromRegistry;
};

let aggConfig;
if (params instanceof AggConfig) {
aggConfig = params;
params.parent = this;
} else {
aggConfig = new AggConfig(this, {
...params,
type: typeof type === 'string' ? this.typesRegistry.get(type) : type,
type: typeof type === 'string' ? getType(type) : type,
});
}

Expand Down

0 comments on commit f193d9c

Please sign in to comment.