diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.getquerylog.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.getquerylog.md deleted file mode 100644 index e933245e81623..0000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.getquerylog.md +++ /dev/null @@ -1,25 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [getQueryLog](./kibana-plugin-plugins-data-public.getquerylog.md) - -## getQueryLog() function - -Signature: - -```typescript -export declare function getQueryLog(uiSettings: IUiSettingsClient, storage: IStorageWrapper, appName: string, language: string): PersistedLog; -``` - -## Parameters - -| Parameter | Type | Description | -| --- | --- | --- | -| uiSettings | IUiSettingsClient | | -| storage | IStorageWrapper | | -| appName | string | | -| language | string | | - -Returns: - -`PersistedLog` - diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md index 8bd38f9e02d11..7cb6ef64431bf 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md @@ -38,7 +38,6 @@ | --- | --- | | [getDefaultQuery(language)](./kibana-plugin-plugins-data-public.getdefaultquery.md) | | | [getEsPreference(uiSettings, sessionId)](./kibana-plugin-plugins-data-public.getespreference.md) | | -| [getQueryLog(uiSettings, storage, appName, language)](./kibana-plugin-plugins-data-public.getquerylog.md) | | | [getSearchErrorType({ message })](./kibana-plugin-plugins-data-public.getsearcherrortype.md) | | | [getSearchParamsFromRequest(searchRequest, dependencies)](./kibana-plugin-plugins-data-public.getsearchparamsfromrequest.md) | | | [getTime(indexPattern, timeRange, options)](./kibana-plugin-plugins-data-public.gettime.md) | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md index a25f4a0c373b2..b168602b64927 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md @@ -7,5 +7,5 @@ Signature: ```typescript -QueryStringInput: React.FC> +QueryStringInput: React.FC> ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.search.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.search.md index 67c4eac67a9e6..6c8f7fbdb170b 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.search.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.search.md @@ -21,6 +21,7 @@ search: { })[]; InvalidEsCalendarIntervalError: typeof InvalidEsCalendarIntervalError; InvalidEsIntervalFormatError: typeof InvalidEsIntervalFormatError; + Ipv4Address: typeof Ipv4Address; isDateHistogramBucketAggConfig: typeof isDateHistogramBucketAggConfig; isNumberType: (agg: import("./search").AggConfig) => boolean; isStringType: (agg: import("./search").AggConfig) => boolean; diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.search.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.search.md index 6020498fdcb6d..09563358100b3 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.search.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.search.md @@ -12,6 +12,7 @@ search: { dateHistogramInterval: typeof dateHistogramInterval; InvalidEsCalendarIntervalError: typeof InvalidEsCalendarIntervalError; InvalidEsIntervalFormatError: typeof InvalidEsIntervalFormatError; + Ipv4Address: typeof Ipv4Address; isValidEsInterval: typeof isValidEsInterval; isValidInterval: typeof isValidInterval; parseEsInterval: typeof parseEsInterval; diff --git a/src/plugins/data/common/search/aggs/index.ts b/src/plugins/data/common/search/aggs/index.ts index 09ea958ccaa85..7a5b7d509c940 100644 --- a/src/plugins/data/common/search/aggs/index.ts +++ b/src/plugins/data/common/search/aggs/index.ts @@ -18,3 +18,4 @@ */ export * from './date_interval_utils'; +export * from './ipv4_address'; diff --git a/src/plugins/kibana_utils/public/parse/ipv4_address.test.ts b/src/plugins/data/common/search/aggs/ipv4_address.test.ts similarity index 99% rename from src/plugins/kibana_utils/public/parse/ipv4_address.test.ts rename to src/plugins/data/common/search/aggs/ipv4_address.test.ts index 1318e11ca6f07..15082b750016e 100644 --- a/src/plugins/kibana_utils/public/parse/ipv4_address.test.ts +++ b/src/plugins/data/common/search/aggs/ipv4_address.test.ts @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -// @ts-ignore + import expect from '@kbn/expect'; import { Ipv4Address } from './ipv4_address'; diff --git a/src/plugins/kibana_utils/public/parse/ipv4_address.ts b/src/plugins/data/common/search/aggs/ipv4_address.ts similarity index 97% rename from src/plugins/kibana_utils/public/parse/ipv4_address.ts rename to src/plugins/data/common/search/aggs/ipv4_address.ts index d214fb6e0e158..da555d8c422ce 100644 --- a/src/plugins/kibana_utils/public/parse/ipv4_address.ts +++ b/src/plugins/data/common/search/aggs/ipv4_address.ts @@ -30,7 +30,6 @@ function isIntegerInRange(integer: number, min: number, max: number) { ); } -// eslint-disable-next-line import/no-default-export export class Ipv4Address { private value: number; diff --git a/src/plugins/data/public/actions/filters/create_filters_from_range_select.test.ts b/src/plugins/data/public/actions/filters/create_filters_from_range_select.test.ts index 5d21b395b994f..aa96d77d873d3 100644 --- a/src/plugins/data/public/actions/filters/create_filters_from_range_select.test.ts +++ b/src/plugins/data/public/actions/filters/create_filters_from_range_select.test.ts @@ -23,8 +23,7 @@ import { createFiltersFromRangeSelectAction } from './create_filters_from_range_ import { IndexPatternsContract, RangeFilter } from '../../../public'; import { dataPluginMock } from '../../../public/mocks'; -import { setIndexPatterns } from '../../../public/services'; -import { mockDataServices } from '../../../public/search/aggs/test_helpers'; +import { setIndexPatterns, setSearchService } from '../../../public/services'; import { TriggerContextMapping } from '../../../../ui_actions/public'; describe('brushEvent', () => { @@ -51,9 +50,10 @@ describe('brushEvent', () => { ]; beforeEach(() => { - mockDataServices(); + const dataStart = dataPluginMock.createStartContract(); + setSearchService(dataStart.search); setIndexPatterns(({ - ...dataPluginMock.createStartContract().indexPatterns, + ...dataStart.indexPatterns, get: async () => indexPattern, } as unknown) as IndexPatternsContract); diff --git a/src/plugins/data/public/actions/filters/create_filters_from_value_click.test.ts b/src/plugins/data/public/actions/filters/create_filters_from_value_click.test.ts index 3e38477a908b8..a3b9b0b344823 100644 --- a/src/plugins/data/public/actions/filters/create_filters_from_value_click.test.ts +++ b/src/plugins/data/public/actions/filters/create_filters_from_value_click.test.ts @@ -24,8 +24,7 @@ import { IndexPatternsContract, } from '../../../public'; import { dataPluginMock } from '../../../public/mocks'; -import { setIndexPatterns } from '../../../public/services'; -import { mockDataServices } from '../../../public/search/aggs/test_helpers'; +import { setIndexPatterns, setSearchService } from '../../../public/services'; import { createFiltersFromValueClickAction } from './create_filters_from_value_click'; import { ValueClickContext } from '../../../../embeddable/public'; @@ -72,9 +71,10 @@ describe('createFiltersFromValueClick', () => { }, ]; - mockDataServices(); + const dataStart = dataPluginMock.createStartContract(); + setSearchService(dataStart.search); setIndexPatterns(({ - ...dataPluginMock.createStartContract().indexPatterns, + ...dataStart.indexPatterns, get: async () => ({ id: 'logstash-*', fields: { diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index 84ee65ed12e3e..abec908b41c0f 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -306,6 +306,7 @@ import { dateHistogramInterval, InvalidEsCalendarIntervalError, InvalidEsIntervalFormatError, + Ipv4Address, isValidEsInterval, isValidInterval, parseEsInterval, @@ -373,6 +374,7 @@ export const search = { intervalOptions, InvalidEsCalendarIntervalError, InvalidEsIntervalFormatError, + Ipv4Address, isDateHistogramBucketAggConfig, // TODO: remove in build_pipeline refactor isNumberType, isStringType, @@ -417,7 +419,6 @@ export { connectToQueryState, syncQueryStateWithUrl, QueryState, - getQueryLog, getDefaultQuery, FilterManager, SavedQuery, diff --git a/src/plugins/data/public/plugin.ts b/src/plugins/data/public/plugin.ts index ec71794fde87d..4040781bb2f01 100644 --- a/src/plugins/data/public/plugin.ts +++ b/src/plugins/data/public/plugin.ts @@ -188,7 +188,11 @@ export class DataPublicPlugin implements Plugin({ timefilter: { timefil // Warning: (ae-missing-release-tag) "createSavedQueryService" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export const createSavedQueryService: (savedObjectsClient: SavedObjectsClientContract_3) => SavedQueryService; +export const createSavedQueryService: (savedObjectsClient: SavedObjectsClientContract) => SavedQueryService; // Warning: (ae-missing-release-tag) "CustomFilter" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // @@ -750,12 +752,6 @@ export const getIndexPatternFieldListCreator: ({ fieldFormats, onNotification, } // @public export const getKbnTypeNames: () => string[]; -// Warning: (ae-forgotten-export) The symbol "PersistedLog" needs to be exported by the entry point index.d.ts -// Warning: (ae-missing-release-tag) "getQueryLog" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) -// -// @public (undocumented) -export function getQueryLog(uiSettings: IUiSettingsClient, storage: IStorageWrapper, appName: string, language: string): PersistedLog; - // Warning: (ae-missing-release-tag) "getSearchErrorType" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -1486,7 +1482,7 @@ export interface QueryState { // Warning: (ae-missing-release-tag) "QueryStringInput" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export const QueryStringInput: React.FC>; +export const QueryStringInput: React.FC>; // @public (undocumented) export type QuerySuggestion = QuerySuggestionBasic | QuerySuggestionField; @@ -1675,6 +1671,7 @@ export const search: { })[]; InvalidEsCalendarIntervalError: typeof InvalidEsCalendarIntervalError; InvalidEsIntervalFormatError: typeof InvalidEsIntervalFormatError; + Ipv4Address: typeof Ipv4Address; isDateHistogramBucketAggConfig: typeof isDateHistogramBucketAggConfig; isNumberType: (agg: import("./search").AggConfig) => boolean; isStringType: (agg: import("./search").AggConfig) => boolean; @@ -1979,20 +1976,21 @@ export const UI_SETTINGS: { // src/plugins/data/public/index.ts:233:27 - (ae-forgotten-export) The symbol "getFromSavedObject" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:233:27 - (ae-forgotten-export) The symbol "flattenHitWrapper" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:233:27 - (ae-forgotten-export) The symbol "formatHitProvider" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:369:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:369:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:369:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:369:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:371:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:372:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:381:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:382:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:383:1 - (ae-forgotten-export) The symbol "isDateHistogramBucketAggConfig" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:387:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:388:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:391:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:392:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:395:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:370:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:370:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:370:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:370:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:372:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:373:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:382:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:383:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:384:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:385:1 - (ae-forgotten-export) The symbol "isDateHistogramBucketAggConfig" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:389:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:390:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:393:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:394:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:397:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts // src/plugins/data/public/query/state_sync/connect_to_query_state.ts:40:60 - (ae-forgotten-export) The symbol "FilterStateStore" needs to be exported by the entry point index.d.ts // src/plugins/data/public/types.ts:52:5 - (ae-forgotten-export) The symbol "createFiltersFromValueClickAction" needs to be exported by the entry point index.d.ts // src/plugins/data/public/types.ts:53:5 - (ae-forgotten-export) The symbol "createFiltersFromRangeSelectAction" needs to be exported by the entry point index.d.ts diff --git a/src/plugins/data/public/query/lib/add_to_query_log.ts b/src/plugins/data/public/query/lib/add_to_query_log.ts new file mode 100644 index 0000000000000..d1e9a800418a2 --- /dev/null +++ b/src/plugins/data/public/query/lib/add_to_query_log.ts @@ -0,0 +1,44 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { IUiSettingsClient } from 'src/core/public'; +import { IStorageWrapper } from 'src/plugins/kibana_utils/public'; +import { Query } from '../../../common'; +import { getQueryLog } from './get_query_log'; + +interface AddToQueryLogDependencies { + uiSettings: IUiSettingsClient; + storage: IStorageWrapper; +} + +export function createAddToQueryLog({ storage, uiSettings }: AddToQueryLogDependencies) { + /** + * This function is to be used in conjunction with ``. + * It provides a way for external editors to add new filter entries to the + * persisted query log which lives in `localStorage`. These entries are then + * read by `` and provided in the autocomplete options. + * + * @param appName Name of the app where this filter is added from. + * @param query Filter value to add. + */ + return function addToQueryLog(appName: string, { language, query }: Query) { + const persistedLog = getQueryLog(uiSettings, storage, appName, language); + persistedLog.add(query); + }; +} diff --git a/src/plugins/data/public/query/lib/get_query_log.ts b/src/plugins/data/public/query/lib/get_query_log.ts index b7827d2c8de02..8256c3eabd7d1 100644 --- a/src/plugins/data/public/query/lib/get_query_log.ts +++ b/src/plugins/data/public/query/lib/get_query_log.ts @@ -22,6 +22,7 @@ import { IStorageWrapper } from 'src/plugins/kibana_utils/public'; import { PersistedLog } from '../persisted_log'; import { UI_SETTINGS } from '../../../common'; +/** @internal */ export function getQueryLog( uiSettings: IUiSettingsClient, storage: IStorageWrapper, diff --git a/src/plugins/data/public/query/lib/index.ts b/src/plugins/data/public/query/lib/index.ts index 284fb6458a535..a0625902fea7b 100644 --- a/src/plugins/data/public/query/lib/index.ts +++ b/src/plugins/data/public/query/lib/index.ts @@ -17,9 +17,10 @@ * under the License. */ -export * from './match_pairs'; +export * from './add_to_query_log'; export * from './from_user'; +export * from './get_default_query'; +export * from './get_query_log'; +export * from './match_pairs'; export * from './to_user'; export * from './to_user'; -export * from './get_query_log'; -export * from './get_default_query'; diff --git a/src/plugins/data/public/query/mocks.ts b/src/plugins/data/public/query/mocks.ts index 47b0a5b871ce2..0c19f71277bc5 100644 --- a/src/plugins/data/public/query/mocks.ts +++ b/src/plugins/data/public/query/mocks.ts @@ -35,10 +35,11 @@ const createSetupContractMock = () => { const createStartContractMock = () => { const startContract: jest.Mocked = { + addToQueryLog: jest.fn(), filterManager: jest.fn() as any, - timefilter: timefilterServiceMock.createStartContract(), savedQueries: jest.fn() as any, state$: new Observable(), + timefilter: timefilterServiceMock.createStartContract(), }; return startContract; diff --git a/src/plugins/data/public/query/query_service.ts b/src/plugins/data/public/query/query_service.ts index c885d596f1943..eb1f985fa51db 100644 --- a/src/plugins/data/public/query/query_service.ts +++ b/src/plugins/data/public/query/query_service.ts @@ -18,9 +18,10 @@ */ import { share } from 'rxjs/operators'; -import { CoreStart } from 'src/core/public'; +import { IUiSettingsClient, SavedObjectsClientContract } from 'src/core/public'; import { IStorageWrapper } from 'src/plugins/kibana_utils/public'; import { FilterManager } from './filter_manager'; +import { createAddToQueryLog } from './lib'; import { TimefilterService, TimefilterSetup } from './timefilter'; import { createSavedQueryService } from './saved_query/saved_query_service'; import { createQueryStateObservable } from './state_sync/create_global_query_observable'; @@ -30,17 +31,24 @@ import { createQueryStateObservable } from './state_sync/create_global_query_obs * @internal */ -export interface QueryServiceDependencies { +interface QueryServiceSetupDependencies { storage: IStorageWrapper; - uiSettings: CoreStart['uiSettings']; + uiSettings: IUiSettingsClient; } + +interface QueryServiceStartDependencies { + savedObjectsClient: SavedObjectsClientContract; + storage: IStorageWrapper; + uiSettings: IUiSettingsClient; +} + export class QueryService { filterManager!: FilterManager; timefilter!: TimefilterSetup; state$!: ReturnType; - public setup({ uiSettings, storage }: QueryServiceDependencies) { + public setup({ storage, uiSettings }: QueryServiceSetupDependencies) { this.filterManager = new FilterManager(uiSettings); const timefilterService = new TimefilterService(); @@ -61,12 +69,16 @@ export class QueryService { }; } - public start(savedObjects: CoreStart['savedObjects']) { + public start({ savedObjectsClient, storage, uiSettings }: QueryServiceStartDependencies) { return { + addToQueryLog: createAddToQueryLog({ + storage, + uiSettings, + }), filterManager: this.filterManager, - timefilter: this.timefilter, + savedQueries: createSavedQueryService(savedObjectsClient), state$: this.state$, - savedQueries: createSavedQueryService(savedObjects.client), + timefilter: this.timefilter, }; } diff --git a/src/plugins/data/public/query/state_sync/connect_to_query_state.test.ts b/src/plugins/data/public/query/state_sync/connect_to_query_state.test.ts index 4e394445b75ae..cf98c87b18267 100644 --- a/src/plugins/data/public/query/state_sync/connect_to_query_state.test.ts +++ b/src/plugins/data/public/query/state_sync/connect_to_query_state.test.ts @@ -78,7 +78,11 @@ describe('connect_to_global_state', () => { uiSettings: setupMock.uiSettings, storage: new Storage(new StubBrowserStorage()), }); - queryServiceStart = queryService.start(startMock.savedObjects); + queryServiceStart = queryService.start({ + uiSettings: setupMock.uiSettings, + storage: new Storage(new StubBrowserStorage()), + savedObjectsClient: startMock.savedObjects.client, + }); filterManager = queryServiceStart.filterManager; timeFilter = queryServiceStart.timefilter.timefilter; @@ -307,7 +311,11 @@ describe('connect_to_app_state', () => { uiSettings: setupMock.uiSettings, storage: new Storage(new StubBrowserStorage()), }); - queryServiceStart = queryService.start(startMock.savedObjects); + queryServiceStart = queryService.start({ + uiSettings: setupMock.uiSettings, + storage: new Storage(new StubBrowserStorage()), + savedObjectsClient: startMock.savedObjects.client, + }); filterManager = queryServiceStart.filterManager; appState = createStateContainer({}); @@ -481,7 +489,11 @@ describe('filters with different state', () => { uiSettings: setupMock.uiSettings, storage: new Storage(new StubBrowserStorage()), }); - queryServiceStart = queryService.start(startMock.savedObjects); + queryServiceStart = queryService.start({ + uiSettings: setupMock.uiSettings, + storage: new Storage(new StubBrowserStorage()), + savedObjectsClient: startMock.savedObjects.client, + }); filterManager = queryServiceStart.filterManager; state = createStateContainer({}); diff --git a/src/plugins/data/public/query/state_sync/sync_state_with_url.test.ts b/src/plugins/data/public/query/state_sync/sync_state_with_url.test.ts index 7727153537257..122eb2ff6a343 100644 --- a/src/plugins/data/public/query/state_sync/sync_state_with_url.test.ts +++ b/src/plugins/data/public/query/state_sync/sync_state_with_url.test.ts @@ -72,7 +72,11 @@ describe('sync_query_state_with_url', () => { uiSettings: setupMock.uiSettings, storage: new Storage(new StubBrowserStorage()), }); - queryServiceStart = queryService.start(startMock.savedObjects); + queryServiceStart = queryService.start({ + uiSettings: startMock.uiSettings, + storage: new Storage(new StubBrowserStorage()), + savedObjectsClient: startMock.savedObjects.client, + }); filterManager = queryServiceStart.filterManager; timefilter = queryServiceStart.timefilter.timefilter; diff --git a/src/plugins/data/public/search/aggs/agg_config.test.ts b/src/plugins/data/public/search/aggs/agg_config.test.ts index 18a86d767c2de..f9279e06d14a9 100644 --- a/src/plugins/data/public/search/aggs/agg_config.test.ts +++ b/src/plugins/data/public/search/aggs/agg_config.test.ts @@ -23,19 +23,50 @@ import { AggConfig, IAggConfig } from './agg_config'; import { AggConfigs, CreateAggConfigParams } from './agg_configs'; import { AggType } from './agg_type'; import { AggTypesRegistryStart } from './agg_types_registry'; -import { mockDataServices, mockAggTypesRegistry } from './test_helpers'; +import { mockAggTypesRegistry } from './test_helpers'; import { MetricAggType } from './metrics/metric_agg_type'; import { IndexPattern, IIndexPatternFieldList } from '../../index_patterns'; -import { stubIndexPatternWithFields } from '../../../public/stubs'; describe('AggConfig', () => { let indexPattern: IndexPattern; let typesRegistry: AggTypesRegistryStart; + const fields = [ + { + name: '@timestamp', + type: 'date', + aggregatable: true, + format: { + toJSON: () => ({}), + }, + }, + { + name: 'bytes', + type: 'number', + aggregatable: true, + format: { + toJSON: () => ({}), + }, + }, + { + name: 'machine.os.keyword', + type: 'string', + aggregatable: true, + format: { + toJSON: () => ({}), + }, + }, + ]; beforeEach(() => { jest.restoreAllMocks(); - mockDataServices(); - indexPattern = stubIndexPatternWithFields as IndexPattern; + indexPattern = { + id: '1234', + title: 'logstash-*', + fields: ({ + getByName: (name: string) => fields.find((f) => f.name === name), + filter: () => fields, + } as unknown) as IndexPattern['fields'], + } as IndexPattern; typesRegistry = mockAggTypesRegistry(); }); @@ -488,6 +519,9 @@ describe('AggConfig', () => { "enabled": Array [ true, ], + "field": Array [ + "machine.os.keyword", + ], "id": Array [ "1", ], @@ -548,6 +582,9 @@ describe('AggConfig', () => { "enabled": Array [ true, ], + "field": Array [ + "bytes", + ], "id": Array [ "1-orderAgg", ], diff --git a/src/plugins/data/public/search/aggs/agg_config.ts b/src/plugins/data/public/search/aggs/agg_config.ts index de49e9ab6f66e..31618eac18e98 100644 --- a/src/plugins/data/public/search/aggs/agg_config.ts +++ b/src/plugins/data/public/search/aggs/agg_config.ts @@ -24,7 +24,7 @@ import { ExpressionAstFunction, ExpressionAstArgument, SerializedFieldFormat, -} from 'src/plugins/expressions/public'; +} from 'src/plugins/expressions/common'; import { IAggType } from './agg_type'; import { writeParams } from './agg_params'; import { IAggConfigs } from './agg_configs'; diff --git a/src/plugins/data/public/search/aggs/agg_configs.test.ts b/src/plugins/data/public/search/aggs/agg_configs.test.ts index f3efeb028665b..df4a5420ae0db 100644 --- a/src/plugins/data/public/search/aggs/agg_configs.test.ts +++ b/src/plugins/data/public/search/aggs/agg_configs.test.ts @@ -21,7 +21,7 @@ import { keyBy } from 'lodash'; import { AggConfig } from './agg_config'; import { AggConfigs } from './agg_configs'; import { AggTypesRegistryStart } from './agg_types_registry'; -import { mockDataServices, mockAggTypesRegistry } from './test_helpers'; +import { mockAggTypesRegistry } from './test_helpers'; import { Field as IndexPatternField, IndexPattern } from '../../index_patterns'; import { stubIndexPattern, stubIndexPatternWithFields } from '../../../public/stubs'; @@ -30,7 +30,6 @@ describe('AggConfigs', () => { let typesRegistry: AggTypesRegistryStart; beforeEach(() => { - mockDataServices(); indexPattern = stubIndexPatternWithFields as IndexPattern; typesRegistry = mockAggTypesRegistry(); }); diff --git a/src/plugins/data/public/search/aggs/agg_params.test.ts b/src/plugins/data/public/search/aggs/agg_params.test.ts index 997027fe88e82..ac3f86d5128a1 100644 --- a/src/plugins/data/public/search/aggs/agg_params.test.ts +++ b/src/plugins/data/public/search/aggs/agg_params.test.ts @@ -22,24 +22,12 @@ import { BaseParamType } from './param_types/base'; import { FieldParamType } from './param_types/field'; import { OptionedParamType } from './param_types/optioned'; import { AggParamType } from '../aggs/param_types/agg'; -import { fieldFormatsServiceMock } from '../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../src/core/public/mocks'; -import { AggTypeDependencies } from './agg_type'; -import { InternalStartServices } from '../../types'; describe('AggParams class', () => { - const aggTypesDependencies: AggTypeDependencies = { - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; - describe('constructor args', () => { it('accepts an array of param defs', () => { const params = [{ name: 'one' }, { name: 'two' }] as AggParamType[]; - const aggParams = initParams(params, aggTypesDependencies); + const aggParams = initParams(params); expect(aggParams).toHaveLength(params.length); expect(Array.isArray(aggParams)).toBeTruthy(); @@ -49,7 +37,7 @@ describe('AggParams class', () => { describe('AggParam creation', () => { it('Uses the FieldParamType class for params with the name "field"', () => { const params = [{ name: 'field', type: 'field' }] as AggParamType[]; - const aggParams = initParams(params, aggTypesDependencies); + const aggParams = initParams(params); expect(aggParams).toHaveLength(params.length); expect(aggParams[0] instanceof FieldParamType).toBeTruthy(); @@ -62,7 +50,7 @@ describe('AggParams class', () => { type: 'optioned', }, ] as AggParamType[]; - const aggParams = initParams(params, aggTypesDependencies); + const aggParams = initParams(params); expect(aggParams).toHaveLength(params.length); expect(aggParams[0] instanceof OptionedParamType).toBeTruthy(); @@ -84,7 +72,7 @@ describe('AggParams class', () => { }, ] as AggParamType[]; - const aggParams = initParams(params, aggTypesDependencies); + const aggParams = initParams(params); expect(aggParams).toHaveLength(params.length); diff --git a/src/plugins/data/public/search/aggs/agg_params.ts b/src/plugins/data/public/search/aggs/agg_params.ts index 4f7bec30fa27d..b6222698a12a6 100644 --- a/src/plugins/data/public/search/aggs/agg_params.ts +++ b/src/plugins/data/public/search/aggs/agg_params.ts @@ -26,7 +26,6 @@ import { BaseParamType } from './param_types/base'; import { AggConfig } from './agg_config'; import { IAggConfigs } from './agg_configs'; -import { AggTypeDependencies } from './agg_type'; const paramTypeMap = { field: FieldParamType, @@ -46,13 +45,12 @@ export interface AggParamOption { } export const initParams = ( - params: TAggParam[], - { getInternalStartServices }: AggTypeDependencies + params: TAggParam[] ): TAggParam[] => params.map((config: TAggParam) => { const Class = paramTypeMap[config.type] || paramTypeMap._default; - return new Class(config, { getInternalStartServices }); + return new Class(config); }) as TAggParam[]; /** diff --git a/src/plugins/data/public/search/aggs/agg_type.test.ts b/src/plugins/data/public/search/aggs/agg_type.test.ts index 99b1c4d861219..2fcc6b97b1cc6 100644 --- a/src/plugins/data/public/search/aggs/agg_type.test.ts +++ b/src/plugins/data/public/search/aggs/agg_type.test.ts @@ -17,33 +17,15 @@ * under the License. */ -import { AggType, AggTypeConfig, AggTypeDependencies } from './agg_type'; +import { AggType, AggTypeConfig } from './agg_type'; import { IAggConfig } from './agg_config'; -import { fieldFormatsServiceMock } from '../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../src/core/public/mocks'; -import { InternalStartServices } from '../../types'; describe('AggType Class', () => { - let dependencies: AggTypeDependencies; - - beforeEach(() => { - dependencies = { - getInternalStartServices: () => - (({ - fieldFormats: { - ...fieldFormatsServiceMock.createStartContract(), - getDefaultInstance: jest.fn(() => 'default') as any, - }, - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; - }); - describe('constructor', () => { test("requires a valid config object as it's first param", () => { expect(() => { const aggConfig: AggTypeConfig = (undefined as unknown) as AggTypeConfig; - new AggType(aggConfig, dependencies); + new AggType(aggConfig); }).toThrowError(); }); @@ -54,7 +36,7 @@ describe('AggType Class', () => { title: 'title', }; - const aggType = new AggType(config, dependencies); + const aggType = new AggType(config); expect(aggType.name).toBe('name'); expect(aggType.title).toBe('title'); @@ -70,7 +52,7 @@ describe('AggType Class', () => { makeLabel, }; - const aggType = new AggType(config, dependencies); + const aggType = new AggType(config); expect(aggType.makeLabel).toBe(makeLabel); expect(aggType.makeLabel(aggConfig)).toBe('label'); @@ -81,15 +63,12 @@ describe('AggType Class', () => { test('copies the value', () => { const testConfig = (aggConfig: IAggConfig) => [aggConfig]; - const aggType = new AggType( - { - name: 'name', - title: 'title', - getResponseAggs: testConfig, - getRequestAggs: testConfig, - }, - dependencies - ); + const aggType = new AggType({ + name: 'name', + title: 'title', + getResponseAggs: testConfig, + getRequestAggs: testConfig, + }); expect(aggType.getResponseAggs).toBe(testConfig); expect(aggType.getResponseAggs).toBe(testConfig); @@ -97,13 +76,10 @@ describe('AggType Class', () => { test('defaults to noop', () => { const aggConfig = {} as IAggConfig; - const aggType = new AggType( - { - name: 'name', - title: 'title', - }, - dependencies - ); + const aggType = new AggType({ + name: 'name', + title: 'title', + }); const responseAggs = aggType.getRequestAggs(aggConfig); expect(responseAggs).toBe(undefined); @@ -112,13 +88,10 @@ describe('AggType Class', () => { describe('params', () => { test('defaults to AggParams object with JSON param', () => { - const aggType = new AggType( - { - name: 'smart agg', - title: 'title', - }, - dependencies - ); + const aggType = new AggType({ + name: 'smart agg', + title: 'title', + }); expect(Array.isArray(aggType.params)).toBeTruthy(); expect(aggType.params.length).toBe(2); @@ -127,14 +100,11 @@ describe('AggType Class', () => { }); test('can disable customLabel', () => { - const aggType = new AggType( - { - name: 'smart agg', - title: 'title', - customLabels: false, - }, - dependencies - ); + const aggType = new AggType({ + name: 'smart agg', + title: 'title', + customLabels: false, + }); expect(aggType.params.length).toBe(1); expect(aggType.params[0].name).toBe('json'); @@ -144,14 +114,11 @@ describe('AggType Class', () => { const params = [{ name: 'one' }, { name: 'two' }]; const paramLength = params.length + 2; // json and custom label are always appended - const aggType = new AggType( - { - name: 'bucketeer', - title: 'title', - params, - }, - dependencies - ); + const aggType = new AggType({ + name: 'bucketeer', + title: 'title', + params, + }); expect(Array.isArray(aggType.params)).toBeTruthy(); expect(aggType.params.length).toBe(paramLength); @@ -170,13 +137,10 @@ describe('AggType Class', () => { }, }, } as unknown) as IAggConfig; - const aggType = new AggType( - { - name: 'name', - title: 'title', - }, - dependencies - ); + const aggType = new AggType({ + name: 'name', + title: 'title', + }); expect(aggType.getSerializedFormat(aggConfig)).toMatchInlineSnapshot(` Object { "id": "format", @@ -188,13 +152,10 @@ describe('AggType Class', () => { const aggConfig = ({ params: {}, } as unknown) as IAggConfig; - const aggType = new AggType( - { - name: 'name', - title: 'title', - }, - dependencies - ); + const aggType = new AggType({ + name: 'name', + title: 'title', + }); expect(aggType.getSerializedFormat(aggConfig)).toMatchInlineSnapshot(`Object {}`); }); @@ -209,14 +170,11 @@ describe('AggType Class', () => { }, } as unknown) as IAggConfig; const getSerializedFormat = jest.fn().mockReturnValue({ id: 'hello' }); - const aggType = new AggType( - { - name: 'name', - title: 'title', - getSerializedFormat, - }, - dependencies - ); + const aggType = new AggType({ + name: 'name', + title: 'title', + getSerializedFormat, + }); const serialized = aggType.getSerializedFormat(aggConfig); expect(getSerializedFormat).toHaveBeenCalledWith(aggConfig); expect(serialized).toMatchInlineSnapshot(` diff --git a/src/plugins/data/public/search/aggs/agg_type.ts b/src/plugins/data/public/search/aggs/agg_type.ts index 13655afdf469e..de7ca48e71d57 100644 --- a/src/plugins/data/public/search/aggs/agg_type.ts +++ b/src/plugins/data/public/search/aggs/agg_type.ts @@ -20,16 +20,15 @@ import { constant, noop, identity } from 'lodash'; import { i18n } from '@kbn/i18n'; -import { SerializedFieldFormat } from 'src/plugins/expressions/public'; +import { SerializedFieldFormat } from 'src/plugins/expressions/common'; +import type { RequestAdapter } from 'src/plugins/inspector/common'; import { initParams } from './agg_params'; import { AggConfig } from './agg_config'; import { IAggConfigs } from './agg_configs'; -import { Adapters } from '../../../../../plugins/inspector/public'; import { BaseParamType } from './param_types/base'; import { AggParamType } from './param_types/agg'; import { ISearchSource } from '../search_source'; -import { GetInternalStartServicesFn } from '../../types'; export interface AggTypeConfig< TAggConfig extends AggConfig = AggConfig, @@ -54,7 +53,7 @@ export interface AggTypeConfig< aggConfigs: IAggConfigs, aggConfig: TAggConfig, searchSource: ISearchSource, - inspectorAdapters: Adapters, + inspectorRequestAdapter: RequestAdapter, abortSignal?: AbortSignal ) => Promise; getSerializedFormat?: (agg: TAggConfig) => SerializedFieldFormat; @@ -65,10 +64,6 @@ export interface AggTypeConfig< // TODO need to make a more explicit interface for this export type IAggType = AggType; -export interface AggTypeDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - export class AggType< TAggConfig extends AggConfig = AggConfig, TParam extends AggParamType = AggParamType @@ -192,7 +187,7 @@ export class AggType< aggConfigs: IAggConfigs, aggConfig: TAggConfig, searchSource: ISearchSource, - inspectorAdapters: Adapters, + inspectorRequestAdapter: RequestAdapter, abortSignal?: AbortSignal ) => Promise; /** @@ -223,10 +218,7 @@ export class AggType< * @private * @param {object} config - used to set the properties of the AggType */ - constructor( - config: AggTypeConfig, - { getInternalStartServices }: AggTypeDependencies - ) { + constructor(config: AggTypeConfig) { this.name = config.name; this.type = config.type || 'metrics'; this.dslName = config.dslName || config.name; @@ -263,7 +255,7 @@ export class AggType< }); } - this.params = initParams(params, { getInternalStartServices }); + this.params = initParams(params); } this.getRequestAggs = config.getRequestAggs || noop; diff --git a/src/plugins/data/public/search/aggs/agg_types.ts b/src/plugins/data/public/search/aggs/agg_types.ts index 68542b66e6c35..2820ae495f318 100644 --- a/src/plugins/data/public/search/aggs/agg_types.ts +++ b/src/plugins/data/public/search/aggs/agg_types.ts @@ -67,40 +67,40 @@ export const getAggTypes = ({ uiSettings, }: AggTypesDependencies) => ({ metrics: [ - getCountMetricAgg({ getInternalStartServices }), - getAvgMetricAgg({ getInternalStartServices }), - getSumMetricAgg({ getInternalStartServices }), - getMedianMetricAgg({ getInternalStartServices }), - getMinMetricAgg({ getInternalStartServices }), - getMaxMetricAgg({ getInternalStartServices }), - getStdDeviationMetricAgg({ getInternalStartServices }), - getCardinalityMetricAgg({ getInternalStartServices }), - getPercentilesMetricAgg({ getInternalStartServices }), + getCountMetricAgg(), + getAvgMetricAgg(), + getSumMetricAgg(), + getMedianMetricAgg(), + getMinMetricAgg(), + getMaxMetricAgg(), + getStdDeviationMetricAgg(), + getCardinalityMetricAgg(), + getPercentilesMetricAgg(), getPercentileRanksMetricAgg({ getInternalStartServices }), - getTopHitMetricAgg({ getInternalStartServices }), - getDerivativeMetricAgg({ getInternalStartServices }), - getCumulativeSumMetricAgg({ getInternalStartServices }), - getMovingAvgMetricAgg({ getInternalStartServices }), - getSerialDiffMetricAgg({ getInternalStartServices }), - getBucketAvgMetricAgg({ getInternalStartServices }), - getBucketSumMetricAgg({ getInternalStartServices }), - getBucketMinMetricAgg({ getInternalStartServices }), - getBucketMaxMetricAgg({ getInternalStartServices }), - getGeoBoundsMetricAgg({ getInternalStartServices }), - getGeoCentroidMetricAgg({ getInternalStartServices }), + getTopHitMetricAgg(), + getDerivativeMetricAgg(), + getCumulativeSumMetricAgg(), + getMovingAvgMetricAgg(), + getSerialDiffMetricAgg(), + getBucketAvgMetricAgg(), + getBucketSumMetricAgg(), + getBucketMinMetricAgg(), + getBucketMaxMetricAgg(), + getGeoBoundsMetricAgg(), + getGeoCentroidMetricAgg(), ], buckets: [ - getDateHistogramBucketAgg({ calculateBounds, uiSettings, getInternalStartServices }), + getDateHistogramBucketAgg({ calculateBounds, uiSettings }), getHistogramBucketAgg({ uiSettings, getInternalStartServices }), getRangeBucketAgg({ getInternalStartServices }), - getDateRangeBucketAgg({ uiSettings, getInternalStartServices }), - getIpRangeBucketAgg({ getInternalStartServices }), - getTermsBucketAgg({ getInternalStartServices }), - getFilterBucketAgg({ getInternalStartServices }), - getFiltersBucketAgg({ uiSettings, getInternalStartServices }), - getSignificantTermsBucketAgg({ getInternalStartServices }), - getGeoHashBucketAgg({ getInternalStartServices }), - getGeoTitleBucketAgg({ getInternalStartServices }), + getDateRangeBucketAgg({ uiSettings }), + getIpRangeBucketAgg(), + getTermsBucketAgg(), + getFilterBucketAgg(), + getFiltersBucketAgg({ uiSettings }), + getSignificantTermsBucketAgg(), + getGeoHashBucketAgg(), + getGeoTitleBucketAgg(), ], }); diff --git a/src/plugins/data/public/search/aggs/buckets/bucket_agg_type.ts b/src/plugins/data/public/search/aggs/buckets/bucket_agg_type.ts index f3c95b444dee9..03629c3189cbb 100644 --- a/src/plugins/data/public/search/aggs/buckets/bucket_agg_type.ts +++ b/src/plugins/data/public/search/aggs/buckets/bucket_agg_type.ts @@ -21,7 +21,6 @@ import { IAggConfig } from '../agg_config'; import { KBN_FIELD_TYPES } from '../../../../common'; import { AggType, AggTypeConfig } from '../agg_type'; import { AggParamType } from '../param_types/agg'; -import { GetInternalStartServicesFn } from '../../../types'; export interface IBucketAggConfig extends IAggConfig { type: InstanceType; @@ -40,10 +39,6 @@ interface BucketAggTypeConfig getKey?: (bucket: any, key: any, agg: IAggConfig) => any; } -interface BucketAggTypeDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - export class BucketAggType extends AggType< TBucketAggConfig, BucketAggParam @@ -51,11 +46,8 @@ export class BucketAggType any; type = bucketType; - constructor( - config: BucketAggTypeConfig, - dependencies: BucketAggTypeDependencies - ) { - super(config, dependencies); + constructor(config: BucketAggTypeConfig) { + super(config); this.getKey = config.getKey || diff --git a/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts b/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts index 518bdbfe0c135..24a17b60566cc 100644 --- a/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts @@ -21,7 +21,7 @@ import moment from 'moment'; import { createFilterDateHistogram } from './date_histogram'; import { intervalOptions } from '../_interval_options'; import { AggConfigs } from '../../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../../test_helpers'; +import { mockAggTypesRegistry } from '../../test_helpers'; import { getDateHistogramBucketAgg, DateHistogramBucketAggDependencies, @@ -29,9 +29,7 @@ import { } from '../date_histogram'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { RangeFilter } from '../../../../../common'; -import { coreMock, notificationServiceMock } from '../../../../../../../core/public/mocks'; -import { fieldFormatsServiceMock } from '../../../../field_formats/mocks'; -import { InternalStartServices } from '../../../../types'; +import { coreMock } from '../../../../../../../core/public/mocks'; describe('AggConfig Filters', () => { describe('date_histogram', () => { @@ -46,15 +44,8 @@ describe('AggConfig Filters', () => { aggTypesDependencies = { calculateBounds: jest.fn(), - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), uiSettings, }; - - mockDataServices(); }); const init = (interval: string = 'auto', duration: any = moment.duration(15, 'minutes')) => { diff --git a/src/plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts b/src/plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts index 08f39e10b6006..c272c037c5927 100644 --- a/src/plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts @@ -26,9 +26,7 @@ import { AggConfigs } from '../../agg_configs'; import { mockAggTypesRegistry } from '../../test_helpers'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../bucket_agg_type'; -import { coreMock, notificationServiceMock } from '../../../../../../../core/public/mocks'; -import { fieldFormatsServiceMock } from '../../../../field_formats/mocks'; -import { InternalStartServices } from '../../../../types'; +import { coreMock } from '../../../../../../../core/public/mocks'; describe('AggConfig Filters', () => { describe('Date range', () => { @@ -37,14 +35,7 @@ describe('AggConfig Filters', () => { beforeEach(() => { const { uiSettings } = coreMock.createSetup(); - aggTypesDependencies = { - uiSettings, - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; + aggTypesDependencies = { uiSettings }; }); const getConfig = (() => {}) as FieldFormatsGetConfigFn; diff --git a/src/plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts b/src/plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts index c5ad1a61e6676..ff66d80c6d8d0 100644 --- a/src/plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts @@ -22,9 +22,7 @@ import { createFilterFilters } from './filters'; import { AggConfigs } from '../../agg_configs'; import { mockAggTypesRegistry } from '../../test_helpers'; import { IBucketAggConfig } from '../bucket_agg_type'; -import { coreMock, notificationServiceMock } from '../../../../../../../core/public/mocks'; -import { fieldFormatsServiceMock } from '../../../../field_formats/mocks'; -import { InternalStartServices } from '../../../../types'; +import { coreMock } from '../../../../../../../core/public/mocks'; describe('AggConfig Filters', () => { describe('filters', () => { @@ -33,14 +31,7 @@ describe('AggConfig Filters', () => { beforeEach(() => { const { uiSettings } = coreMock.createSetup(); - aggTypesDependencies = { - uiSettings, - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; + aggTypesDependencies = { uiSettings }; }); const getAggConfigs = () => { diff --git a/src/plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts b/src/plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts index 89a5fd6577891..852685a505afd 100644 --- a/src/plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts @@ -24,22 +24,10 @@ import { mockAggTypesRegistry } from '../../test_helpers'; import { IpFormat } from '../../../../../common'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../bucket_agg_type'; -import { fieldFormatsServiceMock } from '../../../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../../core/public/mocks'; -import { InternalStartServices } from '../../../../types'; describe('AggConfig Filters', () => { describe('IP range', () => { - const fieldFormats = fieldFormatsServiceMock.createStartContract(); - const typesRegistry = mockAggTypesRegistry([ - getIpRangeBucketAgg({ - getInternalStartServices: () => - (({ - fieldFormats, - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }), - ]); + const typesRegistry = mockAggTypesRegistry([getIpRangeBucketAgg()]); const getAggConfigs = (aggs: CreateAggConfigParams[]) => { const field = { name: 'ip', diff --git a/src/plugins/data/public/search/aggs/buckets/create_filter/range.test.ts b/src/plugins/data/public/search/aggs/buckets/create_filter/range.test.ts index 238e5737d8f47..faffad3beb8c1 100644 --- a/src/plugins/data/public/search/aggs/buckets/create_filter/range.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/create_filter/range.test.ts @@ -17,21 +17,19 @@ * under the License. */ -import { getRangeBucketAgg, RangeBucketAggDependencies } from '../range'; +import { getRangeBucketAgg } from '../range'; import { createFilterRange } from './range'; import { BytesFormat, FieldFormatsGetConfigFn } from '../../../../../common'; import { AggConfigs } from '../../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../../test_helpers'; +import { mockAggTypesRegistry } from '../../test_helpers'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../bucket_agg_type'; import { FieldFormatsStart } from '../../../../field_formats'; import { fieldFormatsServiceMock } from '../../../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../../core/public/mocks'; import { GetInternalStartServicesFn, InternalStartServices } from '../../../../types'; describe('AggConfig Filters', () => { describe('range', () => { - let aggTypesDependencies: RangeBucketAggDependencies; let getInternalStartServices: GetInternalStartServicesFn; let fieldFormats: FieldFormatsStart; @@ -41,17 +39,7 @@ describe('AggConfig Filters', () => { getInternalStartServices = () => (({ fieldFormats, - notifications: notificationServiceMock.createStartContract(), } as unknown) as InternalStartServices); - - aggTypesDependencies = { - getInternalStartServices: () => - (({ - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; - - mockDataServices(); }); const getConfig = (() => {}) as FieldFormatsGetConfigFn; @@ -84,7 +72,7 @@ describe('AggConfig Filters', () => { }, ], { - typesRegistry: mockAggTypesRegistry([getRangeBucketAgg(aggTypesDependencies)]), + typesRegistry: mockAggTypesRegistry([getRangeBucketAgg({ getInternalStartServices })]), } ); }; diff --git a/src/plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts b/src/plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts index a45087916a395..1c165f0d29ab6 100644 --- a/src/plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts @@ -24,25 +24,9 @@ import { mockAggTypesRegistry } from '../../test_helpers'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../bucket_agg_type'; import { Filter, ExistsFilter } from '../../../../../common'; -import { RangeBucketAggDependencies } from '../range'; -import { fieldFormatsServiceMock } from '../../../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../../core/public/mocks'; -import { InternalStartServices } from '../../../../types'; describe('AggConfig Filters', () => { describe('terms', () => { - let aggTypesDependencies: RangeBucketAggDependencies; - - beforeEach(() => { - aggTypesDependencies = { - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; - }); - const getAggConfigs = (aggs: CreateAggConfigParams[]) => { const indexPattern = { id: '1234', @@ -59,7 +43,7 @@ describe('AggConfig Filters', () => { }; return new AggConfigs(indexPattern, aggs, { - typesRegistry: mockAggTypesRegistry([getTermsBucketAgg(aggTypesDependencies)]), + typesRegistry: mockAggTypesRegistry([getTermsBucketAgg()]), }); }; diff --git a/src/plugins/data/public/search/aggs/buckets/date_histogram.ts b/src/plugins/data/public/search/aggs/buckets/date_histogram.ts index e4c4bc0cedc3c..fa1725eccbd28 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_histogram.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_histogram.ts @@ -37,7 +37,6 @@ import { TimeRangeBounds, UI_SETTINGS, } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; import { ExtendedBounds } from './lib/extended_bounds'; @@ -59,7 +58,6 @@ const updateTimeBuckets = ( export interface DateHistogramBucketAggDependencies { calculateBounds: CalculateBoundsFn; - getInternalStartServices: GetInternalStartServicesFn; uiSettings: IUiSettingsClient; } @@ -86,219 +84,213 @@ export interface AggParamsDateHistogram extends BaseAggParams { export const getDateHistogramBucketAgg = ({ calculateBounds, - getInternalStartServices, uiSettings, }: DateHistogramBucketAggDependencies) => - new BucketAggType( - { - name: BUCKET_TYPES.DATE_HISTOGRAM, - title: i18n.translate('data.search.aggs.buckets.dateHistogramTitle', { - defaultMessage: 'Date Histogram', - }), - ordered: { - date: true, - }, - makeLabel(agg) { - let output: Record = {}; + new BucketAggType({ + name: BUCKET_TYPES.DATE_HISTOGRAM, + title: i18n.translate('data.search.aggs.buckets.dateHistogramTitle', { + defaultMessage: 'Date Histogram', + }), + ordered: { + date: true, + }, + makeLabel(agg) { + let output: Record = {}; - if (this.params) { - output = writeParams(this.params, agg); - } + if (this.params) { + output = writeParams(this.params, agg); + } - const field = agg.getFieldDisplayName(); + const field = agg.getFieldDisplayName(); - return i18n.translate('data.search.aggs.buckets.dateHistogramLabel', { - defaultMessage: '{fieldName} per {intervalDescription}', - values: { - fieldName: field, - intervalDescription: output.metricScaleText || output.bucketInterval.description, - }, - }); - }, - createFilter: createFilterDateHistogram, - decorateAggConfig() { - let buckets: any; + return i18n.translate('data.search.aggs.buckets.dateHistogramLabel', { + defaultMessage: '{fieldName} per {intervalDescription}', + values: { + fieldName: field, + intervalDescription: output.metricScaleText || output.bucketInterval.description, + }, + }); + }, + createFilter: createFilterDateHistogram, + decorateAggConfig() { + let buckets: any; - return { - buckets: { - configurable: true, - get() { - if (buckets) return buckets; + return { + buckets: { + configurable: true, + get() { + if (buckets) return buckets; - buckets = new TimeBuckets({ - 'histogram:maxBars': uiSettings.get(UI_SETTINGS.HISTOGRAM_MAX_BARS), - 'histogram:barTarget': uiSettings.get(UI_SETTINGS.HISTOGRAM_BAR_TARGET), - dateFormat: uiSettings.get('dateFormat'), - 'dateFormat:scaled': uiSettings.get('dateFormat:scaled'), - }); - updateTimeBuckets(this, calculateBounds, buckets); + buckets = new TimeBuckets({ + 'histogram:maxBars': uiSettings.get(UI_SETTINGS.HISTOGRAM_MAX_BARS), + 'histogram:barTarget': uiSettings.get(UI_SETTINGS.HISTOGRAM_BAR_TARGET), + dateFormat: uiSettings.get('dateFormat'), + 'dateFormat:scaled': uiSettings.get('dateFormat:scaled'), + }); + updateTimeBuckets(this, calculateBounds, buckets); - return buckets; - }, - } as any, - }; - }, - getSerializedFormat(agg) { - return { - id: 'date', - params: { - pattern: agg.buckets.getScaledDateFormat(), - }, - }; - }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: KBN_FIELD_TYPES.DATE, - default(agg: IBucketDateHistogramAggConfig) { - return agg.getIndexPattern().timeFieldName; - }, - onChange(agg: IBucketDateHistogramAggConfig) { - if (get(agg, 'params.interval') === 'auto' && !agg.fieldIsTimeField()) { - delete agg.params.interval; - } + return buckets; }, + } as any, + }; + }, + getSerializedFormat(agg) { + return { + id: 'date', + params: { + pattern: agg.buckets.getScaledDateFormat(), }, - { - name: 'timeRange', - default: null, - write: noop, - }, - { - name: 'useNormalizedEsInterval', - default: true, - write: noop, + }; + }, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: KBN_FIELD_TYPES.DATE, + default(agg: IBucketDateHistogramAggConfig) { + return agg.getIndexPattern().timeFieldName; }, - { - name: 'scaleMetricValues', - default: false, - write: noop, - advanced: true, + onChange(agg: IBucketDateHistogramAggConfig) { + if (get(agg, 'params.interval') === 'auto' && !agg.fieldIsTimeField()) { + delete agg.params.interval; + } }, - { - name: 'interval', - deserialize(state: any, agg) { - // For upgrading from 7.0.x to 7.1.x - intervals are now stored as key of options or custom value - if (state === 'custom') { - return get(agg, 'params.customInterval'); - } + }, + { + name: 'timeRange', + default: null, + write: noop, + }, + { + name: 'useNormalizedEsInterval', + default: true, + write: noop, + }, + { + name: 'scaleMetricValues', + default: false, + write: noop, + advanced: true, + }, + { + name: 'interval', + deserialize(state: any, agg) { + // For upgrading from 7.0.x to 7.1.x - intervals are now stored as key of options or custom value + if (state === 'custom') { + return get(agg, 'params.customInterval'); + } - const interval = find(intervalOptions, { val: state }); + const interval = find(intervalOptions, { val: state }); - // For upgrading from 4.0.x to 4.1.x - intervals are now stored as 'y' instead of 'year', - // but this maps the old values to the new values - if (!interval && state === 'year') { - return 'y'; - } - return state; - }, - default: 'auto', - options: intervalOptions, - write(agg, output, aggs) { - updateTimeBuckets(agg, calculateBounds); + // For upgrading from 4.0.x to 4.1.x - intervals are now stored as 'y' instead of 'year', + // but this maps the old values to the new values + if (!interval && state === 'year') { + return 'y'; + } + return state; + }, + default: 'auto', + options: intervalOptions, + write(agg, output, aggs) { + updateTimeBuckets(agg, calculateBounds); - const { useNormalizedEsInterval, scaleMetricValues } = agg.params; - const interval = agg.buckets.getInterval(useNormalizedEsInterval); - output.bucketInterval = interval; - if (interval.expression === '0ms') { - // We are hitting this code a couple of times while configuring in editor - // with an interval of 0ms because the overall time range has not yet been - // set. Since 0ms is not a valid ES interval, we cannot pass it through dateHistogramInterval - // below, since it would throw an exception. So in the cases we still have an interval of 0ms - // here we simply skip the rest of the method and never write an interval into the DSL, since - // this DSL will anyway not be used before we're passing this code with an actual interval. - return; - } - output.params = { - ...output.params, - ...dateHistogramInterval(interval.expression), - }; + const { useNormalizedEsInterval, scaleMetricValues } = agg.params; + const interval = agg.buckets.getInterval(useNormalizedEsInterval); + output.bucketInterval = interval; + if (interval.expression === '0ms') { + // We are hitting this code a couple of times while configuring in editor + // with an interval of 0ms because the overall time range has not yet been + // set. Since 0ms is not a valid ES interval, we cannot pass it through dateHistogramInterval + // below, since it would throw an exception. So in the cases we still have an interval of 0ms + // here we simply skip the rest of the method and never write an interval into the DSL, since + // this DSL will anyway not be used before we're passing this code with an actual interval. + return; + } + output.params = { + ...output.params, + ...dateHistogramInterval(interval.expression), + }; - const scaleMetrics = - scaleMetricValues && interval.scaled && interval.scale && interval.scale < 1; - if (scaleMetrics && aggs) { - const metrics = aggs.aggs.filter((a) => isMetricAggType(a.type)); - const all = every(metrics, (a: IBucketAggConfig) => { - const { type } = a; + const scaleMetrics = + scaleMetricValues && interval.scaled && interval.scale && interval.scale < 1; + if (scaleMetrics && aggs) { + const metrics = aggs.aggs.filter((a) => isMetricAggType(a.type)); + const all = every(metrics, (a: IBucketAggConfig) => { + const { type } = a; - if (isMetricAggType(type)) { - return type.isScalable(); - } - }); - if (all) { - output.metricScale = interval.scale; - output.metricScaleText = interval.preScaled?.description || ''; + if (isMetricAggType(type)) { + return type.isScalable(); } + }); + if (all) { + output.metricScale = interval.scale; + output.metricScaleText = interval.preScaled?.description || ''; } - }, - }, - { - name: 'time_zone', - default: undefined, - // We don't ever want this parameter to be serialized out (when saving or to URLs) - // since we do all the logic handling it "on the fly" in the `write` method, to prevent - // time_zones being persisted into saved_objects - serialize: noop, - write(agg, output) { - // If a time_zone has been set explicitly always prefer this. - let tz = agg.params.time_zone; - if (!tz && agg.params.field) { - // If a field has been configured check the index pattern's typeMeta if a date_histogram on that - // field requires a specific time_zone - tz = get(agg.getIndexPattern(), [ - 'typeMeta', - 'aggs', - 'date_histogram', - agg.params.field.name, - 'time_zone', - ]); - } - if (!tz) { - // If the index pattern typeMeta data, didn't had a time zone assigned for the selected field use the configured tz - const isDefaultTimezone = uiSettings.isDefault('dateFormat:tz'); - const detectedTimezone = moment.tz.guess(); - const tzOffset = moment().format('Z'); - tz = isDefaultTimezone - ? detectedTimezone || tzOffset - : uiSettings.get('dateFormat:tz'); - } - output.params.time_zone = tz; - }, - }, - { - name: 'drop_partials', - default: false, - write: noop, - shouldShow: (agg) => { - const field = agg.params.field; - return field && field.name && field.name === agg.getIndexPattern().timeFieldName; - }, + } }, - { - name: 'format', + }, + { + name: 'time_zone', + default: undefined, + // We don't ever want this parameter to be serialized out (when saving or to URLs) + // since we do all the logic handling it "on the fly" in the `write` method, to prevent + // time_zones being persisted into saved_objects + serialize: noop, + write(agg, output) { + // If a time_zone has been set explicitly always prefer this. + let tz = agg.params.time_zone; + if (!tz && agg.params.field) { + // If a field has been configured check the index pattern's typeMeta if a date_histogram on that + // field requires a specific time_zone + tz = get(agg.getIndexPattern(), [ + 'typeMeta', + 'aggs', + 'date_histogram', + agg.params.field.name, + 'time_zone', + ]); + } + if (!tz) { + // If the index pattern typeMeta data, didn't had a time zone assigned for the selected field use the configured tz + const isDefaultTimezone = uiSettings.isDefault('dateFormat:tz'); + const detectedTimezone = moment.tz.guess(); + const tzOffset = moment().format('Z'); + tz = isDefaultTimezone ? detectedTimezone || tzOffset : uiSettings.get('dateFormat:tz'); + } + output.params.time_zone = tz; }, - { - name: 'min_doc_count', - default: 1, + }, + { + name: 'drop_partials', + default: false, + write: noop, + shouldShow: (agg) => { + const field = agg.params.field; + return field && field.name && field.name === agg.getIndexPattern().timeFieldName; }, - { - name: 'extended_bounds', - default: {}, - write(agg, output) { - const val = agg.params.extended_bounds; + }, + { + name: 'format', + }, + { + name: 'min_doc_count', + default: 1, + }, + { + name: 'extended_bounds', + default: {}, + write(agg, output) { + const val = agg.params.extended_bounds; - if (val.min != null || val.max != null) { - output.params.extended_bounds = { - min: moment(val.min).valueOf(), - max: moment(val.max).valueOf(), - }; + if (val.min != null || val.max != null) { + output.params.extended_bounds = { + min: moment(val.min).valueOf(), + max: moment(val.max).valueOf(), + }; - return; - } - }, + return; + } }, - ], - }, - { getInternalStartServices } - ); + }, + ], + }); diff --git a/src/plugins/data/public/search/aggs/buckets/date_histogram_fn.ts b/src/plugins/data/public/search/aggs/buckets/date_histogram_fn.ts index 033b44da0880f..1cc5b41fa6bb3 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_histogram_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_histogram_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/buckets/date_range.test.ts b/src/plugins/data/public/search/aggs/buckets/date_range.test.ts index 0829d6e9cdc9f..69515dfee87fe 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_range.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_range.test.ts @@ -17,13 +17,11 @@ * under the License. */ -import { coreMock, notificationServiceMock } from '../../../../../../../src/core/public/mocks'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; import { getDateRangeBucketAgg, DateRangeBucketAggDependencies } from './date_range'; import { AggConfigs } from '../agg_configs'; import { mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; -import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; -import { InternalStartServices } from '../../../types'; describe('date_range params', () => { let aggTypesDependencies: DateRangeBucketAggDependencies; @@ -31,14 +29,7 @@ describe('date_range params', () => { beforeEach(() => { const { uiSettings } = coreMock.createSetup(); - aggTypesDependencies = { - uiSettings, - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; + aggTypesDependencies = { uiSettings }; }); const getAggConfigs = (params: Record = {}, hasIncludeTypeMeta: boolean = true) => { diff --git a/src/plugins/data/public/search/aggs/buckets/date_range.ts b/src/plugins/data/public/search/aggs/buckets/date_range.ts index dbcf5517fb08f..8c576023f0239 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_range.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_range.ts @@ -28,7 +28,6 @@ import { createFilterDateRange } from './create_filter/date_range'; import { DateRangeKey } from './lib/date_range'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; const dateRangeTitle = i18n.translate('data.search.aggs.buckets.dateRangeTitle', { @@ -37,7 +36,6 @@ const dateRangeTitle = i18n.translate('data.search.aggs.buckets.dateRangeTitle', export interface DateRangeBucketAggDependencies { uiSettings: IUiSettingsClient; - getInternalStartServices: GetInternalStartServicesFn; } export interface AggParamsDateRange extends BaseAggParams { @@ -46,76 +44,68 @@ export interface AggParamsDateRange extends BaseAggParams { time_zone?: string; } -export const getDateRangeBucketAgg = ({ - uiSettings, - getInternalStartServices, -}: DateRangeBucketAggDependencies) => - new BucketAggType( - { - name: BUCKET_TYPES.DATE_RANGE, - title: dateRangeTitle, - createFilter: createFilterDateRange, - getKey({ from, to }): DateRangeKey { - return { from, to }; - }, - getSerializedFormat(agg) { - return { - id: 'date_range', - params: agg.params.field ? agg.params.field.format.toJSON() : {}, - }; - }, - makeLabel(aggConfig) { - return aggConfig.getFieldDisplayName() + ' date ranges'; +export const getDateRangeBucketAgg = ({ uiSettings }: DateRangeBucketAggDependencies) => + new BucketAggType({ + name: BUCKET_TYPES.DATE_RANGE, + title: dateRangeTitle, + createFilter: createFilterDateRange, + getKey({ from, to }): DateRangeKey { + return { from, to }; + }, + getSerializedFormat(agg) { + return { + id: 'date_range', + params: agg.params.field ? agg.params.field.format.toJSON() : {}, + }; + }, + makeLabel(aggConfig) { + return aggConfig.getFieldDisplayName() + ' date ranges'; + }, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: KBN_FIELD_TYPES.DATE, + default(agg: IBucketAggConfig) { + return agg.getIndexPattern().timeFieldName; + }, }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: KBN_FIELD_TYPES.DATE, - default(agg: IBucketAggConfig) { - return agg.getIndexPattern().timeFieldName; + { + name: 'ranges', + default: [ + { + from: 'now-1w/w', + to: 'now', }, - }, - { - name: 'ranges', - default: [ - { - from: 'now-1w/w', - to: 'now', - }, - ], - }, - { - name: 'time_zone', - default: undefined, - // Implimentation method is the same as that of date_histogram - serialize: () => undefined, - write: (agg, output) => { - const field = agg.getParam('field'); - let tz = agg.getParam('time_zone'); + ], + }, + { + name: 'time_zone', + default: undefined, + // Implimentation method is the same as that of date_histogram + serialize: () => undefined, + write: (agg, output) => { + const field = agg.getParam('field'); + let tz = agg.getParam('time_zone'); - if (!tz && field) { - tz = get(agg.getIndexPattern(), [ - 'typeMeta', - 'aggs', - 'date_range', - field.name, - 'time_zone', - ]); - } - if (!tz) { - const detectedTimezone = moment.tz.guess(); - const tzOffset = moment().format('Z'); - const isDefaultTimezone = uiSettings.isDefault('dateFormat:tz'); + if (!tz && field) { + tz = get(agg.getIndexPattern(), [ + 'typeMeta', + 'aggs', + 'date_range', + field.name, + 'time_zone', + ]); + } + if (!tz) { + const detectedTimezone = moment.tz.guess(); + const tzOffset = moment().format('Z'); + const isDefaultTimezone = uiSettings.isDefault('dateFormat:tz'); - tz = isDefaultTimezone - ? detectedTimezone || tzOffset - : uiSettings.get('dateFormat:tz'); - } - output.params.time_zone = tz; - }, + tz = isDefaultTimezone ? detectedTimezone || tzOffset : uiSettings.get('dateFormat:tz'); + } + output.params.time_zone = tz; }, - ], - }, - { getInternalStartServices } - ); + }, + ], + }); diff --git a/src/plugins/data/public/search/aggs/buckets/date_range_fn.ts b/src/plugins/data/public/search/aggs/buckets/date_range_fn.ts index 1fe42ce63d815..5027aadbb7331 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_range_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_range_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/buckets/filter.ts b/src/plugins/data/public/search/aggs/buckets/filter.ts index d048df9f0e43e..5d146e125b996 100644 --- a/src/plugins/data/public/search/aggs/buckets/filter.ts +++ b/src/plugins/data/public/search/aggs/buckets/filter.ts @@ -20,7 +20,6 @@ import { i18n } from '@kbn/i18n'; import { BucketAggType } from './bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; -import { GetInternalStartServicesFn } from '../../../types'; import { GeoBoundingBox } from './lib/geo_point'; import { BaseAggParams } from '../types'; @@ -28,25 +27,18 @@ const filterTitle = i18n.translate('data.search.aggs.buckets.filterTitle', { defaultMessage: 'Filter', }); -export interface FilterBucketAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - export interface AggParamsFilter extends BaseAggParams { geo_bounding_box?: GeoBoundingBox; } -export const getFilterBucketAgg = ({ getInternalStartServices }: FilterBucketAggDependencies) => - new BucketAggType( - { - name: BUCKET_TYPES.FILTER, - title: filterTitle, - makeLabel: () => filterTitle, - params: [ - { - name: 'geo_bounding_box', - }, - ], - }, - { getInternalStartServices } - ); +export const getFilterBucketAgg = () => + new BucketAggType({ + name: BUCKET_TYPES.FILTER, + title: filterTitle, + makeLabel: () => filterTitle, + params: [ + { + name: 'geo_bounding_box', + }, + ], + }); diff --git a/src/plugins/data/public/search/aggs/buckets/filter_fn.ts b/src/plugins/data/public/search/aggs/buckets/filter_fn.ts index 4a7180fc86c71..ae60da3e8a47c 100644 --- a/src/plugins/data/public/search/aggs/buckets/filter_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/filter_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/buckets/filters.test.ts b/src/plugins/data/public/search/aggs/buckets/filters.test.ts index 7554e4081726c..bcb82b5f99649 100644 --- a/src/plugins/data/public/search/aggs/buckets/filters.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/filters.test.ts @@ -18,13 +18,11 @@ */ import { Query } from '../../../../common'; -import { coreMock, notificationServiceMock } from '../../../../../../../src/core/public/mocks'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; import { AggConfigs } from '../agg_configs'; import { mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; import { getFiltersBucketAgg, FiltersBucketAggDependencies } from './filters'; -import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; -import { InternalStartServices } from '../../../types'; describe('Filters Agg', () => { let aggTypesDependencies: FiltersBucketAggDependencies; @@ -33,14 +31,7 @@ describe('Filters Agg', () => { jest.resetAllMocks(); const { uiSettings } = coreMock.createSetup(); - aggTypesDependencies = { - uiSettings, - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; + aggTypesDependencies = { uiSettings }; }); describe('order agg editor UI', () => { diff --git a/src/plugins/data/public/search/aggs/buckets/filters.ts b/src/plugins/data/public/search/aggs/buckets/filters.ts index cb17ef07a930b..cd4ed721fda77 100644 --- a/src/plugins/data/public/search/aggs/buckets/filters.ts +++ b/src/plugins/data/public/search/aggs/buckets/filters.ts @@ -25,10 +25,7 @@ import { createFilterFilters } from './create_filter/filters'; import { toAngularJSON } from '../utils'; import { BucketAggType } from './bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; -import { Storage } from '../../../../../../plugins/kibana_utils/public'; import { getEsQueryConfig, buildEsQuery, Query, UI_SETTINGS } from '../../../../common'; -import { getQueryLog } from '../../../query'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; const filtersTitle = i18n.translate('data.search.aggs.buckets.filtersTitle', { @@ -45,7 +42,6 @@ interface FilterValue { export interface FiltersBucketAggDependencies { uiSettings: IUiSettingsClient; - getInternalStartServices: GetInternalStartServicesFn; } export interface AggParamsFilters extends Omit { @@ -55,81 +51,60 @@ export interface AggParamsFilters extends Omit { }>; } -export const getFiltersBucketAgg = ({ - uiSettings, - getInternalStartServices, -}: FiltersBucketAggDependencies) => - new BucketAggType( - { - name: BUCKET_TYPES.FILTERS, - title: filtersTitle, - createFilter: createFilterFilters, - customLabels: false, - params: [ - { - name: 'filters', - default: [ - { - input: { query: '', language: uiSettings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE) }, - label: '', - }, - ], - write(aggConfig, output) { - const inFilters: FilterValue[] = aggConfig.params.filters; - if (!size(inFilters)) return; - - inFilters.forEach((filter) => { - const persistedLog = getQueryLog( - uiSettings, - new Storage(window.localStorage), - 'vis_default_editor', - filter.input.language - ); - persistedLog.add(filter.input.query); - }); +export const getFiltersBucketAgg = ({ uiSettings }: FiltersBucketAggDependencies) => + new BucketAggType({ + name: BUCKET_TYPES.FILTERS, + title: filtersTitle, + createFilter: createFilterFilters, + customLabels: false, + params: [ + { + name: 'filters', + default: [ + { + input: { query: '', language: uiSettings.get(UI_SETTINGS.SEARCH_QUERY_LANGUAGE) }, + label: '', + }, + ], + write(aggConfig, output) { + const inFilters: FilterValue[] = aggConfig.params.filters; + if (!size(inFilters)) return; - const outFilters = transform( - inFilters, - function (filters: any, filter) { - const input = cloneDeep(filter.input); + const outFilters = transform( + inFilters, + function (filters: Record, filter) { + const input = cloneDeep(filter.input); - if (!input) { - console.log('malformed filter agg params, missing "input" query'); // eslint-disable-line no-console - return; - } + if (!input) { + console.log('malformed filter agg params, missing "input" query'); // eslint-disable-line no-console + return; + } - const esQueryConfigs = getEsQueryConfig(uiSettings); - const query = buildEsQuery( - aggConfig.getIndexPattern(), - [input], - [], - esQueryConfigs - ); + const esQueryConfigs = getEsQueryConfig(uiSettings); + const query = buildEsQuery(aggConfig.getIndexPattern(), [input], [], esQueryConfigs); - if (!query) { - console.log('malformed filter agg params, missing "query" on input'); // eslint-disable-line no-console - return; - } + if (!query) { + console.log('malformed filter agg params, missing "query" on input'); // eslint-disable-line no-console + return; + } - const matchAllLabel = filter.input.query === '' ? '*' : ''; - const label = - filter.label || - matchAllLabel || - (typeof filter.input.query === 'string' - ? filter.input.query - : toAngularJSON(filter.input.query)); - filters[label] = query; - }, - {} - ); + const matchAllLabel = filter.input.query === '' ? '*' : ''; + const label = + filter.label || + matchAllLabel || + (typeof filter.input.query === 'string' + ? filter.input.query + : toAngularJSON(filter.input.query)); + filters[label] = query; + }, + {} + ); - if (!size(outFilters)) return; + if (!size(outFilters)) return; - const params = output.params || (output.params = {}); - params.filters = outFilters; - }, + const params = output.params || (output.params = {}); + params.filters = outFilters; }, - ], - }, - { getInternalStartServices } - ); + }, + ], + }); diff --git a/src/plugins/data/public/search/aggs/buckets/filters_fn.ts b/src/plugins/data/public/search/aggs/buckets/filters_fn.ts index 6ffd5369d7087..55380ea815315 100644 --- a/src/plugins/data/public/search/aggs/buckets/filters_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/filters_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/buckets/geo_hash.test.ts b/src/plugins/data/public/search/aggs/buckets/geo_hash.test.ts index d4c0a5b328844..e77d2bf1eaf5f 100644 --- a/src/plugins/data/public/search/aggs/buckets/geo_hash.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/geo_hash.test.ts @@ -17,29 +17,17 @@ * under the License. */ -import { getGeoHashBucketAgg, GeoHashBucketAggDependencies } from './geo_hash'; +import { getGeoHashBucketAgg } from './geo_hash'; import { AggConfigs, IAggConfigs } from '../agg_configs'; import { mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; -import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; import { BucketAggType, IBucketAggConfig } from './bucket_agg_type'; -import { InternalStartServices } from '../../../types'; describe('Geohash Agg', () => { - let aggTypesDependencies: GeoHashBucketAggDependencies; let geoHashBucketAgg: BucketAggType; beforeEach(() => { - aggTypesDependencies = { - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; - - geoHashBucketAgg = getGeoHashBucketAgg(aggTypesDependencies); + geoHashBucketAgg = getGeoHashBucketAgg(); }); const getAggConfigs = (params?: Record) => { diff --git a/src/plugins/data/public/search/aggs/buckets/geo_hash.ts b/src/plugins/data/public/search/aggs/buckets/geo_hash.ts index fbe7c76681f81..a0ef8a27b0d1e 100644 --- a/src/plugins/data/public/search/aggs/buckets/geo_hash.ts +++ b/src/plugins/data/public/search/aggs/buckets/geo_hash.ts @@ -21,7 +21,6 @@ import { i18n } from '@kbn/i18n'; import { BucketAggType, IBucketAggConfig } from './bucket_agg_type'; import { KBN_FIELD_TYPES } from '../../../../common'; import { BUCKET_TYPES } from './bucket_agg_types'; -import { GetInternalStartServicesFn } from '../../../types'; import { GeoBoundingBox } from './lib/geo_point'; import { BaseAggParams } from '../types'; @@ -36,10 +35,6 @@ const geohashGridTitle = i18n.translate('data.search.aggs.buckets.geohashGridTit defaultMessage: 'Geohash', }); -export interface GeoHashBucketAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - export interface AggParamsGeoHash extends BaseAggParams { field: string; autoPrecision?: boolean; @@ -49,88 +44,85 @@ export interface AggParamsGeoHash extends BaseAggParams { boundingBox?: GeoBoundingBox; } -export const getGeoHashBucketAgg = ({ getInternalStartServices }: GeoHashBucketAggDependencies) => - new BucketAggType( - { - name: BUCKET_TYPES.GEOHASH_GRID, - title: geohashGridTitle, - makeLabel: () => geohashGridTitle, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: KBN_FIELD_TYPES.GEO_POINT, - }, - { - name: 'autoPrecision', - default: true, - write: () => {}, - }, - { - name: 'precision', - default: defaultPrecision, - write(aggConfig, output) { - output.params.precision = aggConfig.params.precision; - }, - }, - { - name: 'useGeocentroid', - default: true, - write: () => {}, - }, - { - name: 'isFilteredByCollar', - default: true, - write: () => {}, - }, - { - name: 'boundingBox', - default: null, - write: () => {}, +export const getGeoHashBucketAgg = () => + new BucketAggType({ + name: BUCKET_TYPES.GEOHASH_GRID, + title: geohashGridTitle, + makeLabel: () => geohashGridTitle, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: KBN_FIELD_TYPES.GEO_POINT, + }, + { + name: 'autoPrecision', + default: true, + write: () => {}, + }, + { + name: 'precision', + default: defaultPrecision, + write(aggConfig, output) { + output.params.precision = aggConfig.params.precision; }, - ], - getRequestAggs(agg) { - const aggs = []; - const params = agg.params; + }, + { + name: 'useGeocentroid', + default: true, + write: () => {}, + }, + { + name: 'isFilteredByCollar', + default: true, + write: () => {}, + }, + { + name: 'boundingBox', + default: null, + write: () => {}, + }, + ], + getRequestAggs(agg) { + const aggs = []; + const params = agg.params; - if (params.isFilteredByCollar && agg.getField()) { - aggs.push( - agg.aggConfigs.createAggConfig( - { - type: 'filter', - id: 'filter_agg', - enabled: true, - params: { - geo_bounding_box: { - ignore_unmapped: true, - [agg.getField().name]: params.boundingBox || defaultBoundingBox, - }, + if (params.isFilteredByCollar && agg.getField()) { + aggs.push( + agg.aggConfigs.createAggConfig( + { + type: 'filter', + id: 'filter_agg', + enabled: true, + params: { + geo_bounding_box: { + ignore_unmapped: true, + [agg.getField().name]: params.boundingBox || defaultBoundingBox, }, - } as any, - { addToAggConfigs: false } - ) - ); - } + }, + } as any, + { addToAggConfigs: false } + ) + ); + } - aggs.push(agg); + aggs.push(agg); - if (params.useGeocentroid) { - aggs.push( - agg.aggConfigs.createAggConfig( - { - type: 'geo_centroid', - enabled: true, - params: { - field: agg.getField(), - }, + if (params.useGeocentroid) { + aggs.push( + agg.aggConfigs.createAggConfig( + { + type: 'geo_centroid', + enabled: true, + params: { + field: agg.getField(), }, - { addToAggConfigs: false } - ) - ); - } + }, + { addToAggConfigs: false } + ) + ); + } - return aggs; - }, + return aggs; }, - { getInternalStartServices } - ); + }); diff --git a/src/plugins/data/public/search/aggs/buckets/geo_hash_fn.ts b/src/plugins/data/public/search/aggs/buckets/geo_hash_fn.ts index bbfa8575d486c..5152804bf8122 100644 --- a/src/plugins/data/public/search/aggs/buckets/geo_hash_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/geo_hash_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/buckets/geo_tile.ts b/src/plugins/data/public/search/aggs/buckets/geo_tile.ts index 1212bba23a93a..e6eff1e1a5d8e 100644 --- a/src/plugins/data/public/search/aggs/buckets/geo_tile.ts +++ b/src/plugins/data/public/search/aggs/buckets/geo_tile.ts @@ -24,13 +24,8 @@ import { BucketAggType, IBucketAggConfig } from './bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; import { METRIC_TYPES } from '../metrics/metric_agg_types'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; -export interface GeoTitleBucketAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const geotileGridTitle = i18n.translate('data.search.aggs.buckets.geotileGridTitle', { defaultMessage: 'Geotile', }); @@ -41,47 +36,44 @@ export interface AggParamsGeoTile extends BaseAggParams { precision?: number; } -export const getGeoTitleBucketAgg = ({ getInternalStartServices }: GeoTitleBucketAggDependencies) => - new BucketAggType( - { - name: BUCKET_TYPES.GEOTILE_GRID, - title: geotileGridTitle, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: KBN_FIELD_TYPES.GEO_POINT, - }, - { - name: 'useGeocentroid', - default: true, - write: noop, - }, - { - name: 'precision', - default: 0, - }, - ], - getRequestAggs(agg) { - const aggs = []; - const useGeocentroid = agg.getParam('useGeocentroid'); +export const getGeoTitleBucketAgg = () => + new BucketAggType({ + name: BUCKET_TYPES.GEOTILE_GRID, + title: geotileGridTitle, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: KBN_FIELD_TYPES.GEO_POINT, + }, + { + name: 'useGeocentroid', + default: true, + write: noop, + }, + { + name: 'precision', + default: 0, + }, + ], + getRequestAggs(agg) { + const aggs = []; + const useGeocentroid = agg.getParam('useGeocentroid'); - aggs.push(agg); + aggs.push(agg); - if (useGeocentroid) { - const aggConfig = { - type: METRIC_TYPES.GEO_CENTROID, - enabled: true, - params: { - field: agg.getField(), - }, - }; + if (useGeocentroid) { + const aggConfig = { + type: METRIC_TYPES.GEO_CENTROID, + enabled: true, + params: { + field: agg.getField(), + }, + }; - aggs.push(agg.aggConfigs.createAggConfig(aggConfig, { addToAggConfigs: false })); - } + aggs.push(agg.aggConfigs.createAggConfig(aggConfig, { addToAggConfigs: false })); + } - return aggs as IBucketAggConfig[]; - }, + return aggs as IBucketAggConfig[]; }, - { getInternalStartServices } - ); + }); diff --git a/src/plugins/data/public/search/aggs/buckets/geo_tile_fn.ts b/src/plugins/data/public/search/aggs/buckets/geo_tile_fn.ts index 9c33ef45762af..ed3142408892a 100644 --- a/src/plugins/data/public/search/aggs/buckets/geo_tile_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/geo_tile_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/buckets/histogram.test.ts b/src/plugins/data/public/search/aggs/buckets/histogram.test.ts index 787603ee14361..6ac77f207d9ce 100644 --- a/src/plugins/data/public/search/aggs/buckets/histogram.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/histogram.test.ts @@ -17,7 +17,7 @@ * under the License. */ -import { coreMock, notificationServiceMock } from '../../../../../../../src/core/public/mocks'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; import { AggConfigs } from '../agg_configs'; import { mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; @@ -42,7 +42,6 @@ describe('Histogram Agg', () => { getInternalStartServices: () => (({ fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), } as unknown) as InternalStartServices), }; }); diff --git a/src/plugins/data/public/search/aggs/buckets/histogram.ts b/src/plugins/data/public/search/aggs/buckets/histogram.ts index ce275e2dc1639..500b6eab75d77 100644 --- a/src/plugins/data/public/search/aggs/buckets/histogram.ts +++ b/src/plugins/data/public/search/aggs/buckets/histogram.ts @@ -57,165 +57,162 @@ export const getHistogramBucketAgg = ({ uiSettings, getInternalStartServices, }: HistogramBucketAggDependencies) => - new BucketAggType( - { - name: BUCKET_TYPES.HISTOGRAM, - title: i18n.translate('data.search.aggs.buckets.histogramTitle', { - defaultMessage: 'Histogram', - }), - ordered: {}, - makeLabel(aggConfig) { - return aggConfig.getFieldDisplayName(); - }, - createFilter: createFilterHistogram(getInternalStartServices), - decorateAggConfig() { - let autoBounds: AutoBounds; - - return { - setAutoBounds: { - configurable: true, - value(newValue: AutoBounds) { - autoBounds = newValue; - }, - }, - getAutoBounds: { - configurable: true, - value() { - return autoBounds; - }, + new BucketAggType({ + name: BUCKET_TYPES.HISTOGRAM, + title: i18n.translate('data.search.aggs.buckets.histogramTitle', { + defaultMessage: 'Histogram', + }), + ordered: {}, + makeLabel(aggConfig) { + return aggConfig.getFieldDisplayName(); + }, + createFilter: createFilterHistogram(getInternalStartServices), + decorateAggConfig() { + let autoBounds: AutoBounds; + + return { + setAutoBounds: { + configurable: true, + value(newValue: AutoBounds) { + autoBounds = newValue; }, - }; - }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: KBN_FIELD_TYPES.NUMBER, }, - { - /* - * This parameter can be set if you want the auto scaled interval to always - * be a multiple of a specific base. - */ - name: 'intervalBase', - default: null, - write: () => {}, + getAutoBounds: { + configurable: true, + value() { + return autoBounds; + }, }, - { - name: 'interval', - modifyAggConfigOnSearchRequestStart( - aggConfig: IBucketHistogramAggConfig, - searchSource: any, - options: any - ) { - const field = aggConfig.getField(); - const aggBody = field.scripted - ? { script: { source: field.script, lang: field.lang } } - : { field: field.name }; - - const childSearchSource = searchSource - .createChild() - .setField('size', 0) - .setField('aggs', { - maxAgg: { - max: aggBody, - }, - minAgg: { - min: aggBody, - }, - }); - - return childSearchSource - .fetch(options) - .then((resp: any) => { - aggConfig.setAutoBounds({ - min: get(resp, 'aggregations.minAgg.value'), - max: get(resp, 'aggregations.maxAgg.value'), - }); - }) - .catch((e: Error) => { - if (e.name === 'AbortError') return; - getInternalStartServices().notifications.toasts.addWarning( - i18n.translate('data.search.aggs.histogram.missingMaxMinValuesWarning', { - defaultMessage: - 'Unable to retrieve max and min values to auto-scale histogram buckets. This may lead to poor visualization performance.', - }) - ); + }; + }, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: KBN_FIELD_TYPES.NUMBER, + }, + { + /* + * This parameter can be set if you want the auto scaled interval to always + * be a multiple of a specific base. + */ + name: 'intervalBase', + default: null, + write: () => {}, + }, + { + name: 'interval', + modifyAggConfigOnSearchRequestStart( + aggConfig: IBucketHistogramAggConfig, + searchSource: any, + options: any + ) { + const field = aggConfig.getField(); + const aggBody = field.scripted + ? { script: { source: field.script, lang: field.lang } } + : { field: field.name }; + + const childSearchSource = searchSource + .createChild() + .setField('size', 0) + .setField('aggs', { + maxAgg: { + max: aggBody, + }, + minAgg: { + min: aggBody, + }, + }); + + return childSearchSource + .fetch(options) + .then((resp: any) => { + aggConfig.setAutoBounds({ + min: get(resp, 'aggregations.minAgg.value'), + max: get(resp, 'aggregations.maxAgg.value'), }); - }, - write(aggConfig, output) { - let interval = parseFloat(aggConfig.params.interval); - if (interval <= 0) { - interval = 1; - } - const autoBounds = aggConfig.getAutoBounds(); - - // ensure interval does not create too many buckets and crash browser - if (autoBounds) { - const range = autoBounds.max - autoBounds.min; - const bars = range / interval; - - if (bars > uiSettings.get(UI_SETTINGS.HISTOGRAM_MAX_BARS)) { - const minInterval = range / uiSettings.get(UI_SETTINGS.HISTOGRAM_MAX_BARS); - - // Round interval by order of magnitude to provide clean intervals - // Always round interval up so there will always be less buckets than histogram:maxBars - const orderOfMagnitude = Math.pow(10, Math.floor(Math.log10(minInterval))); - let roundInterval = orderOfMagnitude; - - while (roundInterval < minInterval) { - roundInterval += orderOfMagnitude; - } - interval = roundInterval; + }) + .catch((e: Error) => { + if (e.name === 'AbortError') return; + throw new Error( + i18n.translate('data.search.aggs.histogram.missingMaxMinValuesWarning', { + defaultMessage: + 'Unable to retrieve max and min values to auto-scale histogram buckets. This may lead to poor visualization performance.', + }) + ); + }); + }, + write(aggConfig, output) { + let interval = parseFloat(aggConfig.params.interval); + if (interval <= 0) { + interval = 1; + } + const autoBounds = aggConfig.getAutoBounds(); + + // ensure interval does not create too many buckets and crash browser + if (autoBounds) { + const range = autoBounds.max - autoBounds.min; + const bars = range / interval; + + if (bars > uiSettings.get(UI_SETTINGS.HISTOGRAM_MAX_BARS)) { + const minInterval = range / uiSettings.get(UI_SETTINGS.HISTOGRAM_MAX_BARS); + + // Round interval by order of magnitude to provide clean intervals + // Always round interval up so there will always be less buckets than histogram:maxBars + const orderOfMagnitude = Math.pow(10, Math.floor(Math.log10(minInterval))); + let roundInterval = orderOfMagnitude; + + while (roundInterval < minInterval) { + roundInterval += orderOfMagnitude; } + interval = roundInterval; } - const base = aggConfig.params.intervalBase; - - if (base) { - if (interval < base) { - // In case the specified interval is below the base, just increase it to it's base - interval = base; - } else if (interval % base !== 0) { - // In case the interval is not a multiple of the base round it to the next base - interval = Math.round(interval / base) * base; - } + } + const base = aggConfig.params.intervalBase; + + if (base) { + if (interval < base) { + // In case the specified interval is below the base, just increase it to it's base + interval = base; + } else if (interval % base !== 0) { + // In case the interval is not a multiple of the base round it to the next base + interval = Math.round(interval / base) * base; } + } - output.params.interval = interval; - }, + output.params.interval = interval; }, - { - name: 'min_doc_count', - default: false, - write(aggConfig, output) { - if (aggConfig.params.min_doc_count) { - output.params.min_doc_count = 0; - } else { - output.params.min_doc_count = 1; - } - }, + }, + { + name: 'min_doc_count', + default: false, + write(aggConfig, output) { + if (aggConfig.params.min_doc_count) { + output.params.min_doc_count = 0; + } else { + output.params.min_doc_count = 1; + } }, - { - name: 'has_extended_bounds', - default: false, - write: () => {}, + }, + { + name: 'has_extended_bounds', + default: false, + write: () => {}, + }, + { + name: 'extended_bounds', + default: { + min: '', + max: '', }, - { - name: 'extended_bounds', - default: { - min: '', - max: '', - }, - write(aggConfig, output) { - const { min, max } = aggConfig.params.extended_bounds; + write(aggConfig, output) { + const { min, max } = aggConfig.params.extended_bounds; - if (aggConfig.params.has_extended_bounds && (min || min === 0) && (max || max === 0)) { - output.params.extended_bounds = { min, max }; - } - }, - shouldShow: (aggConfig: IBucketAggConfig) => aggConfig.params.has_extended_bounds, + if (aggConfig.params.has_extended_bounds && (min || min === 0) && (max || max === 0)) { + output.params.extended_bounds = { min, max }; + } }, - ], - }, - { getInternalStartServices } - ); + shouldShow: (aggConfig: IBucketAggConfig) => aggConfig.params.has_extended_bounds, + }, + ], + }); diff --git a/src/plugins/data/public/search/aggs/buckets/histogram_fn.ts b/src/plugins/data/public/search/aggs/buckets/histogram_fn.ts index 1e5a5a72c0ecb..877fd13e59f87 100644 --- a/src/plugins/data/public/search/aggs/buckets/histogram_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/histogram_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/buckets/ip_range.ts b/src/plugins/data/public/search/aggs/buckets/ip_range.ts index ed9bc5e0462f1..46e0b62d0f8d7 100644 --- a/src/plugins/data/public/search/aggs/buckets/ip_range.ts +++ b/src/plugins/data/public/search/aggs/buckets/ip_range.ts @@ -25,7 +25,6 @@ import { BUCKET_TYPES } from './bucket_agg_types'; import { createFilterIpRange } from './create_filter/ip_range'; import { IpRangeKey, RangeIpRangeAggKey, CidrMaskIpRangeAggKey } from './lib/ip_range'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; const ipRangeTitle = i18n.translate('data.search.aggs.buckets.ipRangeTitle', { @@ -37,10 +36,6 @@ export enum IP_RANGE_TYPES { MASK = 'mask', } -export interface IpRangeBucketAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - export interface AggParamsIpRange extends BaseAggParams { field: string; ipRangeType?: IP_RANGE_TYPES; @@ -50,64 +45,61 @@ export interface AggParamsIpRange extends BaseAggParams { }>; } -export const getIpRangeBucketAgg = ({ getInternalStartServices }: IpRangeBucketAggDependencies) => - new BucketAggType( - { - name: BUCKET_TYPES.IP_RANGE, - title: ipRangeTitle, - createFilter: createFilterIpRange, - getKey(bucket, key, agg): IpRangeKey { - if (agg.params.ipRangeType === IP_RANGE_TYPES.MASK) { - return { type: 'mask', mask: key }; - } - return { type: 'range', from: bucket.from, to: bucket.to }; - }, - getSerializedFormat(agg) { - return { - id: 'ip_range', - params: agg.params.field ? agg.params.field.format.toJSON() : {}, - }; +export const getIpRangeBucketAgg = () => + new BucketAggType({ + name: BUCKET_TYPES.IP_RANGE, + title: ipRangeTitle, + createFilter: createFilterIpRange, + getKey(bucket, key, agg): IpRangeKey { + if (agg.params.ipRangeType === IP_RANGE_TYPES.MASK) { + return { type: 'mask', mask: key }; + } + return { type: 'range', from: bucket.from, to: bucket.to }; + }, + getSerializedFormat(agg) { + return { + id: 'ip_range', + params: agg.params.field ? agg.params.field.format.toJSON() : {}, + }; + }, + makeLabel(aggConfig) { + return i18n.translate('data.search.aggs.buckets.ipRangeLabel', { + defaultMessage: '{fieldName} IP ranges', + values: { + fieldName: aggConfig.getFieldDisplayName(), + }, + }); + }, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: KBN_FIELD_TYPES.IP, }, - makeLabel(aggConfig) { - return i18n.translate('data.search.aggs.buckets.ipRangeLabel', { - defaultMessage: '{fieldName} IP ranges', - values: { - fieldName: aggConfig.getFieldDisplayName(), - }, - }); + { + name: 'ipRangeType', + default: IP_RANGE_TYPES.FROM_TO, + write: noop, }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: KBN_FIELD_TYPES.IP, - }, - { - name: 'ipRangeType', - default: IP_RANGE_TYPES.FROM_TO, - write: noop, + { + name: 'ranges', + default: { + fromTo: [ + { from: '0.0.0.0', to: '127.255.255.255' }, + { from: '128.0.0.0', to: '191.255.255.255' }, + ], + mask: [{ mask: '0.0.0.0/1' }, { mask: '128.0.0.0/2' }], }, - { - name: 'ranges', - default: { - fromTo: [ - { from: '0.0.0.0', to: '127.255.255.255' }, - { from: '128.0.0.0', to: '191.255.255.255' }, - ], - mask: [{ mask: '0.0.0.0/1' }, { mask: '128.0.0.0/2' }], - }, - write(aggConfig, output) { - const ipRangeType = aggConfig.params.ipRangeType; - let ranges = aggConfig.params.ranges[ipRangeType]; + write(aggConfig, output) { + const ipRangeType = aggConfig.params.ipRangeType; + let ranges = aggConfig.params.ranges[ipRangeType]; - if (ipRangeType === IP_RANGE_TYPES.FROM_TO) { - ranges = map(ranges, (range: any) => omitBy(range, isNull)); - } + if (ipRangeType === IP_RANGE_TYPES.FROM_TO) { + ranges = map(ranges, (range: any) => omitBy(range, isNull)); + } - output.params.ranges = ranges; - }, + output.params.ranges = ranges; }, - ], - }, - { getInternalStartServices } - ); + }, + ], + }); diff --git a/src/plugins/data/public/search/aggs/buckets/ip_range_fn.ts b/src/plugins/data/public/search/aggs/buckets/ip_range_fn.ts index 554a8708d9164..15b763fd42d6b 100644 --- a/src/plugins/data/public/search/aggs/buckets/ip_range_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/ip_range_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/buckets/lib/cidr_mask.ts b/src/plugins/data/public/search/aggs/buckets/lib/cidr_mask.ts index 4535b5f5c5dd2..57a7b378f305f 100644 --- a/src/plugins/data/public/search/aggs/buckets/lib/cidr_mask.ts +++ b/src/plugins/data/public/search/aggs/buckets/lib/cidr_mask.ts @@ -17,7 +17,7 @@ * under the License. */ -import { Ipv4Address } from '../../../../../../../plugins/kibana_utils/public'; +import { Ipv4Address } from '../../../../../common'; const NUM_BITS = 32; diff --git a/src/plugins/data/public/search/aggs/buckets/lib/time_buckets/time_buckets.test.ts b/src/plugins/data/public/search/aggs/buckets/lib/time_buckets/time_buckets.test.ts index af3c15167295c..ae7630ecd3dac 100644 --- a/src/plugins/data/public/search/aggs/buckets/lib/time_buckets/time_buckets.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/lib/time_buckets/time_buckets.test.ts @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + import moment from 'moment'; import { TimeBuckets, TimeBucketsConfig } from './time_buckets'; diff --git a/src/plugins/data/public/search/aggs/buckets/range.test.ts b/src/plugins/data/public/search/aggs/buckets/range.test.ts index fea5572b75795..f7c61a638158c 100644 --- a/src/plugins/data/public/search/aggs/buckets/range.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/range.test.ts @@ -19,10 +19,10 @@ import { getRangeBucketAgg, RangeBucketAggDependencies } from './range'; import { AggConfigs } from '../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; +import { mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; import { FieldFormatsGetConfigFn, NumberFormat } from '../../../../common'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; +import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; import { InternalStartServices } from '../../../types'; describe('Range Agg', () => { @@ -32,11 +32,9 @@ describe('Range Agg', () => { aggTypesDependencies = { getInternalStartServices: () => (({ - notifications: notificationServiceMock.createStartContract(), + fieldFormats: fieldFormatsServiceMock.createStartContract(), } as unknown) as InternalStartServices), }; - - mockDataServices(); }); const getConfig = (() => {}) as FieldFormatsGetConfigFn; diff --git a/src/plugins/data/public/search/aggs/buckets/range.ts b/src/plugins/data/public/search/aggs/buckets/range.ts index 92c5193d55a20..9f54f9fd0704e 100644 --- a/src/plugins/data/public/search/aggs/buckets/range.ts +++ b/src/plugins/data/public/search/aggs/buckets/range.ts @@ -45,66 +45,63 @@ export interface AggParamsRange extends BaseAggParams { export const getRangeBucketAgg = ({ getInternalStartServices }: RangeBucketAggDependencies) => { const keyCaches = new WeakMap(); - return new BucketAggType( - { - name: BUCKET_TYPES.RANGE, - title: rangeTitle, - createFilter: createFilterRange(getInternalStartServices), - makeLabel(aggConfig) { - return i18n.translate('data.search.aggs.aggTypesLabel', { - defaultMessage: '{fieldName} ranges', - values: { - fieldName: aggConfig.getFieldDisplayName(), - }, - }); - }, - getKey(bucket, key, agg) { - let keys = keyCaches.get(agg); + return new BucketAggType({ + name: BUCKET_TYPES.RANGE, + title: rangeTitle, + createFilter: createFilterRange(getInternalStartServices), + makeLabel(aggConfig) { + return i18n.translate('data.search.aggs.aggTypesLabel', { + defaultMessage: '{fieldName} ranges', + values: { + fieldName: aggConfig.getFieldDisplayName(), + }, + }); + }, + getKey(bucket, key, agg) { + let keys = keyCaches.get(agg); - if (!keys) { - keys = new Map(); - keyCaches.set(agg, keys); - } + if (!keys) { + keys = new Map(); + keyCaches.set(agg, keys); + } - const id = RangeKey.idBucket(bucket); + const id = RangeKey.idBucket(bucket); - key = keys.get(id); - if (!key) { - key = new RangeKey(bucket); - keys.set(id, key); - } + key = keys.get(id); + if (!key) { + key = new RangeKey(bucket); + keys.set(id, key); + } - return key; - }, - getSerializedFormat(agg) { - const format = agg.params.field ? agg.params.field.format.toJSON() : {}; - return { - id: 'range', - params: { - id: format.id, - params: format.params, - }, - }; - }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: [KBN_FIELD_TYPES.NUMBER], - }, - { - name: 'ranges', - default: [ - { from: 0, to: 1000 }, - { from: 1000, to: 2000 }, - ], - write(aggConfig, output) { - output.params.ranges = aggConfig.params.ranges; - output.params.keyed = true; - }, + return key; + }, + getSerializedFormat(agg) { + const format = agg.params.field ? agg.params.field.format.toJSON() : {}; + return { + id: 'range', + params: { + id: format.id, + params: format.params, }, - ], + }; }, - { getInternalStartServices } - ); + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: [KBN_FIELD_TYPES.NUMBER], + }, + { + name: 'ranges', + default: [ + { from: 0, to: 1000 }, + { from: 1000, to: 2000 }, + ], + write(aggConfig, output) { + output.params.ranges = aggConfig.params.ranges; + output.params.keyed = true; + }, + }, + ], + }); }; diff --git a/src/plugins/data/public/search/aggs/buckets/range_fn.ts b/src/plugins/data/public/search/aggs/buckets/range_fn.ts index 48686e7061de9..6806125a10f6d 100644 --- a/src/plugins/data/public/search/aggs/buckets/range_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/range_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/buckets/significant_terms.test.ts b/src/plugins/data/public/search/aggs/buckets/significant_terms.test.ts index 8fe833aa99cb2..f13fafc2b17e6 100644 --- a/src/plugins/data/public/search/aggs/buckets/significant_terms.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/significant_terms.test.ts @@ -20,29 +20,11 @@ import { AggConfigs, IAggConfigs } from '../agg_configs'; import { mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; -import { - getSignificantTermsBucketAgg, - SignificantTermsBucketAggDependencies, -} from './significant_terms'; -import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; -import { InternalStartServices } from '../../../types'; +import { getSignificantTermsBucketAgg } from './significant_terms'; describe('Significant Terms Agg', () => { describe('order agg editor UI', () => { describe('convert include/exclude from old format', () => { - let aggTypesDependencies: SignificantTermsBucketAggDependencies; - - beforeEach(() => { - aggTypesDependencies = { - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; - }); - const getAggConfigs = (params: Record = {}) => { const indexPattern = { id: '1234', @@ -69,9 +51,7 @@ describe('Significant Terms Agg', () => { }, ], { - typesRegistry: mockAggTypesRegistry([ - getSignificantTermsBucketAgg(aggTypesDependencies), - ]), + typesRegistry: mockAggTypesRegistry([getSignificantTermsBucketAgg()]), } ); }; diff --git a/src/plugins/data/public/search/aggs/buckets/significant_terms.ts b/src/plugins/data/public/search/aggs/buckets/significant_terms.ts index e6afc56dfd31c..4dc8aafd8a7a7 100644 --- a/src/plugins/data/public/search/aggs/buckets/significant_terms.ts +++ b/src/plugins/data/public/search/aggs/buckets/significant_terms.ts @@ -23,17 +23,12 @@ import { createFilterTerms } from './create_filter/terms'; import { isStringType, migrateIncludeExcludeFormat } from './migrate_include_exclude_format'; import { BUCKET_TYPES } from './bucket_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; const significantTermsTitle = i18n.translate('data.search.aggs.buckets.significantTermsTitle', { defaultMessage: 'Significant Terms', }); -export interface SignificantTermsBucketAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - export interface AggParamsSignificantTerms extends BaseAggParams { field: string; size?: number; @@ -41,57 +36,50 @@ export interface AggParamsSignificantTerms extends BaseAggParams { include?: string; } -export const getSignificantTermsBucketAgg = ({ - getInternalStartServices, -}: SignificantTermsBucketAggDependencies) => - new BucketAggType( - { - name: BUCKET_TYPES.SIGNIFICANT_TERMS, - title: significantTermsTitle, - makeLabel(aggConfig) { - return i18n.translate('data.search.aggs.buckets.significantTermsLabel', { - defaultMessage: 'Top {size} unusual terms in {fieldName}', - values: { - size: aggConfig.params.size, - fieldName: aggConfig.getFieldDisplayName(), - }, - }); - }, - createFilter: createFilterTerms, - params: [ - { - name: 'field', - type: 'field', - scriptable: false, - filterFieldTypes: KBN_FIELD_TYPES.STRING, - }, - { - name: 'size', - default: '', - }, - { - name: 'exclude', - displayName: i18n.translate('data.search.aggs.buckets.significantTerms.excludeLabel', { - defaultMessage: 'Exclude', - }), - type: 'string', - advanced: true, - shouldShow: isStringType, - ...migrateIncludeExcludeFormat, +export const getSignificantTermsBucketAgg = () => + new BucketAggType({ + name: BUCKET_TYPES.SIGNIFICANT_TERMS, + title: significantTermsTitle, + makeLabel(aggConfig) { + return i18n.translate('data.search.aggs.buckets.significantTermsLabel', { + defaultMessage: 'Top {size} unusual terms in {fieldName}', + values: { + size: aggConfig.params.size, + fieldName: aggConfig.getFieldDisplayName(), }, - { - name: 'include', - displayName: i18n.translate('data.search.aggs.buckets.significantTerms.includeLabel', { - defaultMessage: 'Include', - }), - type: 'string', - advanced: true, - shouldShow: isStringType, - ...migrateIncludeExcludeFormat, - }, - ], + }); }, - { - getInternalStartServices, - } - ); + createFilter: createFilterTerms, + params: [ + { + name: 'field', + type: 'field', + scriptable: false, + filterFieldTypes: KBN_FIELD_TYPES.STRING, + }, + { + name: 'size', + default: '', + }, + { + name: 'exclude', + displayName: i18n.translate('data.search.aggs.buckets.significantTerms.excludeLabel', { + defaultMessage: 'Exclude', + }), + type: 'string', + advanced: true, + shouldShow: isStringType, + ...migrateIncludeExcludeFormat, + }, + { + name: 'include', + displayName: i18n.translate('data.search.aggs.buckets.significantTerms.includeLabel', { + defaultMessage: 'Include', + }), + type: 'string', + advanced: true, + shouldShow: isStringType, + ...migrateIncludeExcludeFormat, + }, + ], + }); diff --git a/src/plugins/data/public/search/aggs/buckets/significant_terms_fn.ts b/src/plugins/data/public/search/aggs/buckets/significant_terms_fn.ts index 83583070bddfe..1fecfcc914313 100644 --- a/src/plugins/data/public/search/aggs/buckets/significant_terms_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/significant_terms_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/buckets/terms.ts b/src/plugins/data/public/search/aggs/buckets/terms.ts index 57a5ebf72316c..d3acd33d73d01 100644 --- a/src/plugins/data/public/search/aggs/buckets/terms.ts +++ b/src/plugins/data/public/search/aggs/buckets/terms.ts @@ -19,6 +19,7 @@ import { noop } from 'lodash'; import { i18n } from '@kbn/i18n'; + import { BucketAggType, IBucketAggConfig } from './bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; import { createFilterTerms } from './create_filter/terms'; @@ -26,10 +27,8 @@ import { isStringOrNumberType, migrateIncludeExcludeFormat, } from './migrate_include_exclude_format'; -import { AggConfigSerialized, BaseAggParams, IAggConfigs } from '../types'; +import { AggConfigSerialized, BaseAggParams } from '../types'; -import { Adapters } from '../../../../../inspector/public'; -import { ISearchSource } from '../../search_source'; import { KBN_FIELD_TYPES } from '../../../../common'; import { getRequestInspectorStats, getResponseInspectorStats } from '../../expressions'; @@ -38,7 +37,6 @@ import { mergeOtherBucketAggResponse, updateMissingBucket, } from './_terms_other_bucket_helper'; -import { GetInternalStartServicesFn } from '../../../types'; export const termsAggFilter = [ '!top_hits', @@ -59,10 +57,6 @@ const termsTitle = i18n.translate('data.search.aggs.buckets.termsTitle', { defaultMessage: 'Terms', }); -export interface TermsBucketAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - export interface AggParamsTerms extends BaseAggParams { field: string; orderBy: string; @@ -78,222 +72,219 @@ export interface AggParamsTerms extends BaseAggParams { include?: string; } -export const getTermsBucketAgg = ({ getInternalStartServices }: TermsBucketAggDependencies) => - new BucketAggType( - { - name: BUCKET_TYPES.TERMS, - expressionName: 'aggTerms', - title: termsTitle, - makeLabel(agg) { - const params = agg.params; - return agg.getFieldDisplayName() + ': ' + params.order.text; - }, - getSerializedFormat(agg) { - const format = agg.params.field ? agg.params.field.format.toJSON() : {}; - return { - id: 'terms', - params: { - id: format.id, - otherBucketLabel: agg.params.otherBucketLabel, - missingBucketLabel: agg.params.missingBucketLabel, - ...format.params, - }, - }; - }, - createFilter: createFilterTerms, - postFlightRequest: async ( - resp: any, - aggConfigs: IAggConfigs, - aggConfig: IBucketAggConfig, - searchSource: ISearchSource, - inspectorAdapters: Adapters, - abortSignal?: AbortSignal - ) => { - if (!resp.aggregations) return resp; - const nestedSearchSource = searchSource.createChild(); - if (aggConfig.params.otherBucket) { - const filterAgg = buildOtherBucketAgg(aggConfigs, aggConfig, resp); - if (!filterAgg) return resp; +export const getTermsBucketAgg = () => + new BucketAggType({ + name: BUCKET_TYPES.TERMS, + expressionName: 'aggTerms', + title: termsTitle, + makeLabel(agg) { + const params = agg.params; + return agg.getFieldDisplayName() + ': ' + params.order.text; + }, + getSerializedFormat(agg) { + const format = agg.params.field ? agg.params.field.format.toJSON() : {}; + return { + id: 'terms', + params: { + id: format.id, + otherBucketLabel: agg.params.otherBucketLabel, + missingBucketLabel: agg.params.missingBucketLabel, + ...format.params, + }, + }; + }, + createFilter: createFilterTerms, + postFlightRequest: async ( + resp, + aggConfigs, + aggConfig, + searchSource, + inspectorRequestAdapter, + abortSignal + ) => { + if (!resp.aggregations) return resp; + const nestedSearchSource = searchSource.createChild(); + if (aggConfig.params.otherBucket) { + const filterAgg = buildOtherBucketAgg(aggConfigs, aggConfig, resp); + if (!filterAgg) return resp; - nestedSearchSource.setField('aggs', filterAgg); + nestedSearchSource.setField('aggs', filterAgg); - const request = inspectorAdapters.requests.start( - i18n.translate('data.search.aggs.buckets.terms.otherBucketTitle', { - defaultMessage: 'Other bucket', + const request = inspectorRequestAdapter.start( + i18n.translate('data.search.aggs.buckets.terms.otherBucketTitle', { + defaultMessage: 'Other bucket', + }), + { + description: i18n.translate('data.search.aggs.buckets.terms.otherBucketDescription', { + defaultMessage: + 'This request counts the number of documents that fall ' + + 'outside the criterion of the data buckets.', }), - { - description: i18n.translate('data.search.aggs.buckets.terms.otherBucketDescription', { - defaultMessage: - 'This request counts the number of documents that fall ' + - 'outside the criterion of the data buckets.', - }), - } - ); - nestedSearchSource.getSearchRequestBody().then((body: string) => { - request.json(body); - }); - request.stats(getRequestInspectorStats(nestedSearchSource)); + } + ); + nestedSearchSource.getSearchRequestBody().then((body) => { + request.json(body); + }); + request.stats(getRequestInspectorStats(nestedSearchSource)); - const response = await nestedSearchSource.fetch({ abortSignal }); - request - .stats(getResponseInspectorStats(nestedSearchSource, response)) - .ok({ json: response }); - resp = mergeOtherBucketAggResponse(aggConfigs, resp, response, aggConfig, filterAgg()); - } - if (aggConfig.params.missingBucket) { - resp = updateMissingBucket(resp, aggConfigs, aggConfig); - } - return resp; + const response = await nestedSearchSource.fetch({ abortSignal }); + request + .stats(getResponseInspectorStats(nestedSearchSource, response)) + .ok({ json: response }); + resp = mergeOtherBucketAggResponse(aggConfigs, resp, response, aggConfig, filterAgg()); + } + if (aggConfig.params.missingBucket) { + resp = updateMissingBucket(resp, aggConfigs, aggConfig); + } + return resp; + }, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: [ + KBN_FIELD_TYPES.NUMBER, + KBN_FIELD_TYPES.BOOLEAN, + KBN_FIELD_TYPES.DATE, + KBN_FIELD_TYPES.IP, + KBN_FIELD_TYPES.STRING, + ], }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: [ - KBN_FIELD_TYPES.NUMBER, - KBN_FIELD_TYPES.BOOLEAN, - KBN_FIELD_TYPES.DATE, - KBN_FIELD_TYPES.IP, - KBN_FIELD_TYPES.STRING, - ], - }, - { - name: 'orderBy', - write: noop, // prevent default write, it's handled by orderAgg - }, - { - name: 'orderAgg', - type: 'agg', - allowedAggs: termsAggFilter, - default: null, - makeAgg(termsAgg, state = { type: 'count' }) { - state.schema = 'orderAgg'; - const orderAgg = termsAgg.aggConfigs.createAggConfig(state, { - addToAggConfigs: false, - }); - orderAgg.id = termsAgg.id + '-orderAgg'; + { + name: 'orderBy', + write: noop, // prevent default write, it's handled by orderAgg + }, + { + name: 'orderAgg', + type: 'agg', + allowedAggs: termsAggFilter, + default: null, + makeAgg(termsAgg, state = { type: 'count' }) { + state.schema = 'orderAgg'; + const orderAgg = termsAgg.aggConfigs.createAggConfig(state, { + addToAggConfigs: false, + }); + orderAgg.id = termsAgg.id + '-orderAgg'; - return orderAgg; - }, - write(agg, output, aggs) { - const dir = agg.params.order.value; - const order: Record = (output.params.order = {}); + return orderAgg; + }, + write(agg, output, aggs) { + const dir = agg.params.order.value; + const order: Record = (output.params.order = {}); - let orderAgg = agg.params.orderAgg || aggs!.getResponseAggById(agg.params.orderBy); + let orderAgg = agg.params.orderAgg || aggs!.getResponseAggById(agg.params.orderBy); - // TODO: This works around an Elasticsearch bug the always casts terms agg scripts to strings - // thus causing issues with filtering. This probably causes other issues since float might not - // be able to contain the number on the elasticsearch side - if (output.params.script) { - output.params.value_type = - agg.getField().type === 'number' ? 'float' : agg.getField().type; - } + // TODO: This works around an Elasticsearch bug the always casts terms agg scripts to strings + // thus causing issues with filtering. This probably causes other issues since float might not + // be able to contain the number on the elasticsearch side + if (output.params.script) { + output.params.value_type = + agg.getField().type === 'number' ? 'float' : agg.getField().type; + } - if (agg.params.missingBucket && agg.params.field.type === 'string') { - output.params.missing = '__missing__'; - } + if (agg.params.missingBucket && agg.params.field.type === 'string') { + output.params.missing = '__missing__'; + } - if (!orderAgg) { - order[agg.params.orderBy || '_count'] = dir; - return; - } + if (!orderAgg) { + order[agg.params.orderBy || '_count'] = dir; + return; + } - if (orderAgg.type.name === 'count') { - order._count = dir; - return; - } + if (orderAgg.type.name === 'count') { + order._count = dir; + return; + } - const orderAggId = orderAgg.id; + const orderAggId = orderAgg.id; - if (orderAgg.parentId && aggs) { - orderAgg = aggs.byId(orderAgg.parentId); - } + if (orderAgg.parentId && aggs) { + orderAgg = aggs.byId(orderAgg.parentId); + } - output.subAggs = (output.subAggs || []).concat(orderAgg); - order[orderAggId] = dir; - }, - }, - { - name: 'order', - type: 'optioned', - default: 'desc', - options: [ - { - text: i18n.translate('data.search.aggs.buckets.terms.orderDescendingTitle', { - defaultMessage: 'Descending', - }), - value: 'desc', - }, - { - text: i18n.translate('data.search.aggs.buckets.terms.orderAscendingTitle', { - defaultMessage: 'Ascending', - }), - value: 'asc', - }, - ], - write: noop, // prevent default write, it's handled by orderAgg - }, - { - name: 'size', - default: 5, + output.subAggs = (output.subAggs || []).concat(orderAgg); + order[orderAggId] = dir; }, - { - name: 'otherBucket', - default: false, - write: noop, - }, - { - name: 'otherBucketLabel', - type: 'string', - default: i18n.translate('data.search.aggs.buckets.terms.otherBucketLabel', { - defaultMessage: 'Other', - }), - displayName: i18n.translate('data.search.aggs.otherBucket.labelForOtherBucketLabel', { - defaultMessage: 'Label for other bucket', - }), - shouldShow: (agg) => agg.getParam('otherBucket'), - write: noop, - }, - { - name: 'missingBucket', - default: false, - write: noop, - }, - { - name: 'missingBucketLabel', - default: i18n.translate('data.search.aggs.buckets.terms.missingBucketLabel', { - defaultMessage: 'Missing', - description: `Default label used in charts when documents are missing a field. + }, + { + name: 'order', + type: 'optioned', + default: 'desc', + options: [ + { + text: i18n.translate('data.search.aggs.buckets.terms.orderDescendingTitle', { + defaultMessage: 'Descending', + }), + value: 'desc', + }, + { + text: i18n.translate('data.search.aggs.buckets.terms.orderAscendingTitle', { + defaultMessage: 'Ascending', + }), + value: 'asc', + }, + ], + write: noop, // prevent default write, it's handled by orderAgg + }, + { + name: 'size', + default: 5, + }, + { + name: 'otherBucket', + default: false, + write: noop, + }, + { + name: 'otherBucketLabel', + type: 'string', + default: i18n.translate('data.search.aggs.buckets.terms.otherBucketLabel', { + defaultMessage: 'Other', + }), + displayName: i18n.translate('data.search.aggs.otherBucket.labelForOtherBucketLabel', { + defaultMessage: 'Label for other bucket', + }), + shouldShow: (agg) => agg.getParam('otherBucket'), + write: noop, + }, + { + name: 'missingBucket', + default: false, + write: noop, + }, + { + name: 'missingBucketLabel', + default: i18n.translate('data.search.aggs.buckets.terms.missingBucketLabel', { + defaultMessage: 'Missing', + description: `Default label used in charts when documents are missing a field. Visible when you create a chart with a terms aggregation and enable "Show missing values"`, - }), - type: 'string', - displayName: i18n.translate('data.search.aggs.otherBucket.labelForMissingValuesLabel', { - defaultMessage: 'Label for missing values', - }), - shouldShow: (agg) => agg.getParam('missingBucket'), - write: noop, - }, - { - name: 'exclude', - displayName: i18n.translate('data.search.aggs.buckets.terms.excludeLabel', { - defaultMessage: 'Exclude', - }), - type: 'string', - advanced: true, - shouldShow: isStringOrNumberType, - ...migrateIncludeExcludeFormat, - }, - { - name: 'include', - displayName: i18n.translate('data.search.aggs.buckets.terms.includeLabel', { - defaultMessage: 'Include', - }), - type: 'string', - advanced: true, - shouldShow: isStringOrNumberType, - ...migrateIncludeExcludeFormat, - }, - ], - }, - { getInternalStartServices } - ); + }), + type: 'string', + displayName: i18n.translate('data.search.aggs.otherBucket.labelForMissingValuesLabel', { + defaultMessage: 'Label for missing values', + }), + shouldShow: (agg) => agg.getParam('missingBucket'), + write: noop, + }, + { + name: 'exclude', + displayName: i18n.translate('data.search.aggs.buckets.terms.excludeLabel', { + defaultMessage: 'Exclude', + }), + type: 'string', + advanced: true, + shouldShow: isStringOrNumberType, + ...migrateIncludeExcludeFormat, + }, + { + name: 'include', + displayName: i18n.translate('data.search.aggs.buckets.terms.includeLabel', { + defaultMessage: 'Include', + }), + type: 'string', + advanced: true, + shouldShow: isStringOrNumberType, + ...migrateIncludeExcludeFormat, + }, + ], + }); diff --git a/src/plugins/data/public/search/aggs/buckets/terms_fn.ts b/src/plugins/data/public/search/aggs/buckets/terms_fn.ts index 49520863fe1cc..975941506da4e 100644 --- a/src/plugins/data/public/search/aggs/buckets/terms_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/terms_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/avg.ts b/src/plugins/data/public/search/aggs/metrics/avg.ts index 1aa39ccd2aad9..651aaf857c757 100644 --- a/src/plugins/data/public/search/aggs/metrics/avg.ts +++ b/src/plugins/data/public/search/aggs/metrics/avg.ts @@ -21,7 +21,6 @@ import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; const averageTitle = i18n.translate('data.search.aggs.metrics.averageTitle', { @@ -32,31 +31,22 @@ export interface AggParamsAvg extends BaseAggParams { field: string; } -export interface AvgMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - -export const getAvgMetricAgg = ({ getInternalStartServices }: AvgMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.AVG, - title: averageTitle, - makeLabel: (aggConfig) => { - return i18n.translate('data.search.aggs.metrics.averageLabel', { - defaultMessage: 'Average {field}', - values: { field: aggConfig.getFieldDisplayName() }, - }); - }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.HISTOGRAM], - }, - ], +export const getAvgMetricAgg = () => { + return new MetricAggType({ + name: METRIC_TYPES.AVG, + title: averageTitle, + makeLabel: (aggConfig) => { + return i18n.translate('data.search.aggs.metrics.averageLabel', { + defaultMessage: 'Average {field}', + values: { field: aggConfig.getFieldDisplayName() }, + }); }, - { - getInternalStartServices, - } - ); + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.HISTOGRAM], + }, + ], + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/avg_fn.ts b/src/plugins/data/public/search/aggs/metrics/avg_fn.ts index c370623b2752a..18629927d7814 100644 --- a/src/plugins/data/public/search/aggs/metrics/avg_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/avg_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts b/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts index a30e426dd2390..92fa675ac2d38 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts @@ -24,17 +24,12 @@ import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; import { METRIC_TYPES } from './metric_agg_types'; import { AggConfigSerialized, BaseAggParams } from '../types'; -import { GetInternalStartServicesFn } from '../../../types'; export interface AggParamsBucketAvg extends BaseAggParams { customMetric?: AggConfigSerialized; customBucket?: AggConfigSerialized; } -export interface BucketAvgMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const overallAverageLabel = i18n.translate('data.search.aggs.metrics.overallAverageLabel', { defaultMessage: 'overall average', }); @@ -43,36 +38,29 @@ const averageBucketTitle = i18n.translate('data.search.aggs.metrics.averageBucke defaultMessage: 'Average Bucket', }); -export const getBucketAvgMetricAgg = ({ - getInternalStartServices, -}: BucketAvgMetricAggDependencies) => { +export const getBucketAvgMetricAgg = () => { const { subtype, params, getSerializedFormat } = siblingPipelineAggHelper; - return new MetricAggType( - { - name: METRIC_TYPES.AVG_BUCKET, - title: averageBucketTitle, - makeLabel: (agg) => makeNestedLabel(agg, overallAverageLabel), - subtype, - params: [...params()], - getSerializedFormat, - getValue(agg, bucket) { - const customMetric = agg.getParam('customMetric'); - const customBucket = agg.getParam('customBucket'); - const scaleMetrics = customMetric.type && customMetric.type.isScalable(); + return new MetricAggType({ + name: METRIC_TYPES.AVG_BUCKET, + title: averageBucketTitle, + makeLabel: (agg) => makeNestedLabel(agg, overallAverageLabel), + subtype, + params: [...params()], + getSerializedFormat, + getValue(agg, bucket) { + const customMetric = agg.getParam('customMetric'); + const customBucket = agg.getParam('customBucket'); + const scaleMetrics = customMetric.type && customMetric.type.isScalable(); - let value = bucket[agg.id] && bucket[agg.id].value; + let value = bucket[agg.id] && bucket[agg.id].value; - if (scaleMetrics && customBucket.type.name === 'date_histogram') { - const aggInfo = customBucket.write(); + if (scaleMetrics && customBucket.type.name === 'date_histogram') { + const aggInfo = customBucket.write(); - value *= get(aggInfo, 'bucketInterval.scale', 1); - } - return value; - }, + value *= get(aggInfo, 'bucketInterval.scale', 1); + } + return value; }, - { - getInternalStartServices, - } - ); + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_avg_fn.ts b/src/plugins/data/public/search/aggs/metrics/bucket_avg_fn.ts index 56643a2df54bd..4e0c1d7311cd6 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_avg_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_avg_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_max.ts b/src/plugins/data/public/search/aggs/metrics/bucket_max.ts index 307c7ed3f9d38..8e2606676ec33 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_max.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_max.ts @@ -23,17 +23,12 @@ import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; import { METRIC_TYPES } from './metric_agg_types'; import { AggConfigSerialized, BaseAggParams } from '../types'; -import { GetInternalStartServicesFn } from '../../../types'; export interface AggParamsBucketMax extends BaseAggParams { customMetric?: AggConfigSerialized; customBucket?: AggConfigSerialized; } -export interface BucketMaxMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const overallMaxLabel = i18n.translate('data.search.aggs.metrics.overallMaxLabel', { defaultMessage: 'overall max', }); @@ -42,22 +37,15 @@ const maxBucketTitle = i18n.translate('data.search.aggs.metrics.maxBucketTitle', defaultMessage: 'Max Bucket', }); -export const getBucketMaxMetricAgg = ({ - getInternalStartServices, -}: BucketMaxMetricAggDependencies) => { +export const getBucketMaxMetricAgg = () => { const { subtype, params, getSerializedFormat } = siblingPipelineAggHelper; - return new MetricAggType( - { - name: METRIC_TYPES.MAX_BUCKET, - title: maxBucketTitle, - makeLabel: (agg) => makeNestedLabel(agg, overallMaxLabel), - subtype, - params: [...params()], - getSerializedFormat, - }, - { - getInternalStartServices, - } - ); + return new MetricAggType({ + name: METRIC_TYPES.MAX_BUCKET, + title: maxBucketTitle, + makeLabel: (agg) => makeNestedLabel(agg, overallMaxLabel), + subtype, + params: [...params()], + getSerializedFormat, + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_max_fn.ts b/src/plugins/data/public/search/aggs/metrics/bucket_max_fn.ts index 896e9cf839605..66ae7601470fb 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_max_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_max_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_min.ts b/src/plugins/data/public/search/aggs/metrics/bucket_min.ts index bb4ed9d44b0b3..dedc3a9de3dd1 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_min.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_min.ts @@ -23,17 +23,12 @@ import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; import { METRIC_TYPES } from './metric_agg_types'; import { AggConfigSerialized, BaseAggParams } from '../types'; -import { GetInternalStartServicesFn } from '../../../types'; export interface AggParamsBucketMin extends BaseAggParams { customMetric?: AggConfigSerialized; customBucket?: AggConfigSerialized; } -export interface BucketMinMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const overallMinLabel = i18n.translate('data.search.aggs.metrics.overallMinLabel', { defaultMessage: 'overall min', }); @@ -42,22 +37,15 @@ const minBucketTitle = i18n.translate('data.search.aggs.metrics.minBucketTitle', defaultMessage: 'Min Bucket', }); -export const getBucketMinMetricAgg = ({ - getInternalStartServices, -}: BucketMinMetricAggDependencies) => { +export const getBucketMinMetricAgg = () => { const { subtype, params, getSerializedFormat } = siblingPipelineAggHelper; - return new MetricAggType( - { - name: METRIC_TYPES.MIN_BUCKET, - title: minBucketTitle, - makeLabel: (agg) => makeNestedLabel(agg, overallMinLabel), - subtype, - params: [...params()], - getSerializedFormat, - }, - { - getInternalStartServices, - } - ); + return new MetricAggType({ + name: METRIC_TYPES.MIN_BUCKET, + title: minBucketTitle, + makeLabel: (agg) => makeNestedLabel(agg, overallMinLabel), + subtype, + params: [...params()], + getSerializedFormat, + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_min_fn.ts b/src/plugins/data/public/search/aggs/metrics/bucket_min_fn.ts index 2ae3d9211227a..009cc0102b05d 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_min_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_min_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts b/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts index dd065b52acd12..c6ccd498a0eb9 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts @@ -23,17 +23,12 @@ import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; import { METRIC_TYPES } from './metric_agg_types'; import { AggConfigSerialized, BaseAggParams } from '../types'; -import { GetInternalStartServicesFn } from '../../../types'; export interface AggParamsBucketSum extends BaseAggParams { customMetric?: AggConfigSerialized; customBucket?: AggConfigSerialized; } -export interface BucketSumMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const overallSumLabel = i18n.translate('data.search.aggs.metrics.overallSumLabel', { defaultMessage: 'overall sum', }); @@ -42,22 +37,15 @@ const sumBucketTitle = i18n.translate('data.search.aggs.metrics.sumBucketTitle', defaultMessage: 'Sum Bucket', }); -export const getBucketSumMetricAgg = ({ - getInternalStartServices, -}: BucketSumMetricAggDependencies) => { +export const getBucketSumMetricAgg = () => { const { subtype, params, getSerializedFormat } = siblingPipelineAggHelper; - return new MetricAggType( - { - name: METRIC_TYPES.SUM_BUCKET, - title: sumBucketTitle, - makeLabel: (agg) => makeNestedLabel(agg, overallSumLabel), - subtype, - params: [...params()], - getSerializedFormat, - }, - { - getInternalStartServices, - } - ); + return new MetricAggType({ + name: METRIC_TYPES.SUM_BUCKET, + title: sumBucketTitle, + makeLabel: (agg) => makeNestedLabel(agg, overallSumLabel), + subtype, + params: [...params()], + getSerializedFormat, + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_sum_fn.ts b/src/plugins/data/public/search/aggs/metrics/bucket_sum_fn.ts index eceb11a90f293..920285e89e8f4 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_sum_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_sum_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/cardinality.ts b/src/plugins/data/public/search/aggs/metrics/cardinality.ts index efc79a8559566..777cb833849f4 100644 --- a/src/plugins/data/public/search/aggs/metrics/cardinality.ts +++ b/src/plugins/data/public/search/aggs/metrics/cardinality.ts @@ -21,7 +21,6 @@ import { i18n } from '@kbn/i18n'; import { MetricAggType, IMetricAggConfig } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; const uniqueCountTitle = i18n.translate('data.search.aggs.metrics.uniqueCountTitle', { @@ -32,39 +31,28 @@ export interface AggParamsCardinality extends BaseAggParams { field: string; } -export interface CardinalityMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - -export const getCardinalityMetricAgg = ({ - getInternalStartServices, -}: CardinalityMetricAggDependencies) => - new MetricAggType( - { - name: METRIC_TYPES.CARDINALITY, - title: uniqueCountTitle, - makeLabel(aggConfig: IMetricAggConfig) { - return i18n.translate('data.search.aggs.metrics.uniqueCountLabel', { - defaultMessage: 'Unique count of {field}', - values: { field: aggConfig.getFieldDisplayName() }, - }); - }, - getSerializedFormat(agg) { - return { - id: 'number', - }; - }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: Object.values(KBN_FIELD_TYPES).filter( - (type) => type !== KBN_FIELD_TYPES.HISTOGRAM - ), - }, - ], +export const getCardinalityMetricAgg = () => + new MetricAggType({ + name: METRIC_TYPES.CARDINALITY, + title: uniqueCountTitle, + makeLabel(aggConfig: IMetricAggConfig) { + return i18n.translate('data.search.aggs.metrics.uniqueCountLabel', { + defaultMessage: 'Unique count of {field}', + values: { field: aggConfig.getFieldDisplayName() }, + }); + }, + getSerializedFormat(agg) { + return { + id: 'number', + }; }, - { - getInternalStartServices, - } - ); + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: Object.values(KBN_FIELD_TYPES).filter( + (type) => type !== KBN_FIELD_TYPES.HISTOGRAM + ), + }, + ], + }); diff --git a/src/plugins/data/public/search/aggs/metrics/cardinality_fn.ts b/src/plugins/data/public/search/aggs/metrics/cardinality_fn.ts index f30429993638f..2542c76e7be57 100644 --- a/src/plugins/data/public/search/aggs/metrics/cardinality_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/cardinality_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/count.ts b/src/plugins/data/public/search/aggs/metrics/count.ts index 86faca053a9cf..d990599586e81 100644 --- a/src/plugins/data/public/search/aggs/metrics/count.ts +++ b/src/plugins/data/public/search/aggs/metrics/count.ts @@ -20,38 +20,28 @@ import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; -import { GetInternalStartServicesFn } from '../../../types'; -export interface CountMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - -export const getCountMetricAgg = ({ getInternalStartServices }: CountMetricAggDependencies) => - new MetricAggType( - { - name: METRIC_TYPES.COUNT, - title: i18n.translate('data.search.aggs.metrics.countTitle', { +export const getCountMetricAgg = () => + new MetricAggType({ + name: METRIC_TYPES.COUNT, + title: i18n.translate('data.search.aggs.metrics.countTitle', { + defaultMessage: 'Count', + }), + hasNoDsl: true, + makeLabel() { + return i18n.translate('data.search.aggs.metrics.countLabel', { defaultMessage: 'Count', - }), - hasNoDsl: true, - makeLabel() { - return i18n.translate('data.search.aggs.metrics.countLabel', { - defaultMessage: 'Count', - }); - }, - getSerializedFormat(agg) { - return { - id: 'number', - }; - }, - getValue(agg, bucket) { - return bucket.doc_count; - }, - isScalable() { - return true; - }, + }); + }, + getSerializedFormat(agg) { + return { + id: 'number', + }; + }, + getValue(agg, bucket) { + return bucket.doc_count; + }, + isScalable() { + return true; }, - { - getInternalStartServices, - } - ); + }); diff --git a/src/plugins/data/public/search/aggs/metrics/count_fn.ts b/src/plugins/data/public/search/aggs/metrics/count_fn.ts index f4c7e8e854230..338ca18209299 100644 --- a/src/plugins/data/public/search/aggs/metrics/count_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/count_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts b/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts index 3de88bb71740f..b10bdd31a5817 100644 --- a/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts +++ b/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts @@ -23,7 +23,6 @@ import { parentPipelineAggHelper } from './lib/parent_pipeline_agg_helper'; import { makeNestedLabel } from './lib/make_nested_label'; import { METRIC_TYPES } from './metric_agg_types'; import { AggConfigSerialized, BaseAggParams } from '../types'; -import { GetInternalStartServicesFn } from '../../../types'; export interface AggParamsCumulativeSum extends BaseAggParams { buckets_path: string; @@ -31,10 +30,6 @@ export interface AggParamsCumulativeSum extends BaseAggParams { metricAgg?: string; } -export interface CumulativeSumMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const cumulativeSumLabel = i18n.translate('data.search.aggs.metrics.cumulativeSumLabel', { defaultMessage: 'cumulative sum', }); @@ -43,22 +38,15 @@ const cumulativeSumTitle = i18n.translate('data.search.aggs.metrics.cumulativeSu defaultMessage: 'Cumulative Sum', }); -export const getCumulativeSumMetricAgg = ({ - getInternalStartServices, -}: CumulativeSumMetricAggDependencies) => { +export const getCumulativeSumMetricAgg = () => { const { subtype, params, getSerializedFormat } = parentPipelineAggHelper; - return new MetricAggType( - { - name: METRIC_TYPES.CUMULATIVE_SUM, - title: cumulativeSumTitle, - makeLabel: (agg) => makeNestedLabel(agg, cumulativeSumLabel), - subtype, - params: [...params()], - getSerializedFormat, - }, - { - getInternalStartServices, - } - ); + return new MetricAggType({ + name: METRIC_TYPES.CUMULATIVE_SUM, + title: cumulativeSumTitle, + makeLabel: (agg) => makeNestedLabel(agg, cumulativeSumLabel), + subtype, + params: [...params()], + getSerializedFormat, + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/cumulative_sum_fn.ts b/src/plugins/data/public/search/aggs/metrics/cumulative_sum_fn.ts index 950df03b10134..411cbd256c37e 100644 --- a/src/plugins/data/public/search/aggs/metrics/cumulative_sum_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/cumulative_sum_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/derivative.ts b/src/plugins/data/public/search/aggs/metrics/derivative.ts index c9507029080e6..c03c33ba80710 100644 --- a/src/plugins/data/public/search/aggs/metrics/derivative.ts +++ b/src/plugins/data/public/search/aggs/metrics/derivative.ts @@ -23,7 +23,6 @@ import { parentPipelineAggHelper } from './lib/parent_pipeline_agg_helper'; import { makeNestedLabel } from './lib/make_nested_label'; import { METRIC_TYPES } from './metric_agg_types'; import { AggConfigSerialized, BaseAggParams } from '../types'; -import { GetInternalStartServicesFn } from '../../../types'; export interface AggParamsDerivative extends BaseAggParams { buckets_path: string; @@ -31,10 +30,6 @@ export interface AggParamsDerivative extends BaseAggParams { metricAgg?: string; } -export interface DerivativeMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const derivativeLabel = i18n.translate('data.search.aggs.metrics.derivativeLabel', { defaultMessage: 'derivative', }); @@ -43,24 +38,17 @@ const derivativeTitle = i18n.translate('data.search.aggs.metrics.derivativeTitle defaultMessage: 'Derivative', }); -export const getDerivativeMetricAgg = ({ - getInternalStartServices, -}: DerivativeMetricAggDependencies) => { +export const getDerivativeMetricAgg = () => { const { subtype, params, getSerializedFormat } = parentPipelineAggHelper; - return new MetricAggType( - { - name: METRIC_TYPES.DERIVATIVE, - title: derivativeTitle, - makeLabel(agg) { - return makeNestedLabel(agg, derivativeLabel); - }, - subtype, - params: [...params()], - getSerializedFormat, + return new MetricAggType({ + name: METRIC_TYPES.DERIVATIVE, + title: derivativeTitle, + makeLabel(agg) { + return makeNestedLabel(agg, derivativeLabel); }, - { - getInternalStartServices, - } - ); + subtype, + params: [...params()], + getSerializedFormat, + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/derivative_fn.ts b/src/plugins/data/public/search/aggs/metrics/derivative_fn.ts index 90b88b4de2712..1d87dfdac6da3 100644 --- a/src/plugins/data/public/search/aggs/metrics/derivative_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/derivative_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/geo_bounds.ts b/src/plugins/data/public/search/aggs/metrics/geo_bounds.ts index 864e97ca8dfe7..c86f42f066bdf 100644 --- a/src/plugins/data/public/search/aggs/metrics/geo_bounds.ts +++ b/src/plugins/data/public/search/aggs/metrics/geo_bounds.ts @@ -21,17 +21,12 @@ import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; export interface AggParamsGeoBounds extends BaseAggParams { field: string; } -export interface GeoBoundsMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const geoBoundsTitle = i18n.translate('data.search.aggs.metrics.geoBoundsTitle', { defaultMessage: 'Geo Bounds', }); @@ -40,24 +35,17 @@ const geoBoundsLabel = i18n.translate('data.search.aggs.metrics.geoBoundsLabel', defaultMessage: 'Geo Bounds', }); -export const getGeoBoundsMetricAgg = ({ - getInternalStartServices, -}: GeoBoundsMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.GEO_BOUNDS, - title: geoBoundsTitle, - makeLabel: () => geoBoundsLabel, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: KBN_FIELD_TYPES.GEO_POINT, - }, - ], - }, - { - getInternalStartServices, - } - ); +export const getGeoBoundsMetricAgg = () => { + return new MetricAggType({ + name: METRIC_TYPES.GEO_BOUNDS, + title: geoBoundsTitle, + makeLabel: () => geoBoundsLabel, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: KBN_FIELD_TYPES.GEO_POINT, + }, + ], + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/geo_bounds_fn.ts b/src/plugins/data/public/search/aggs/metrics/geo_bounds_fn.ts index 8ba71a098fc70..927f7f42d0f50 100644 --- a/src/plugins/data/public/search/aggs/metrics/geo_bounds_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/geo_bounds_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/geo_centroid.ts b/src/plugins/data/public/search/aggs/metrics/geo_centroid.ts index 2bbb6b2de8d87..b98ce45d35229 100644 --- a/src/plugins/data/public/search/aggs/metrics/geo_centroid.ts +++ b/src/plugins/data/public/search/aggs/metrics/geo_centroid.ts @@ -21,17 +21,12 @@ import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; export interface AggParamsGeoCentroid extends BaseAggParams { field: string; } -export interface GeoCentroidMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const geoCentroidTitle = i18n.translate('data.search.aggs.metrics.geoCentroidTitle', { defaultMessage: 'Geo Centroid', }); @@ -40,27 +35,20 @@ const geoCentroidLabel = i18n.translate('data.search.aggs.metrics.geoCentroidLab defaultMessage: 'Geo Centroid', }); -export const getGeoCentroidMetricAgg = ({ - getInternalStartServices, -}: GeoCentroidMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.GEO_CENTROID, - title: geoCentroidTitle, - makeLabel: () => geoCentroidLabel, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: KBN_FIELD_TYPES.GEO_POINT, - }, - ], - getValue(agg, bucket) { - return bucket[agg.id] && bucket[agg.id].location; +export const getGeoCentroidMetricAgg = () => { + return new MetricAggType({ + name: METRIC_TYPES.GEO_CENTROID, + title: geoCentroidTitle, + makeLabel: () => geoCentroidLabel, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: KBN_FIELD_TYPES.GEO_POINT, }, + ], + getValue(agg, bucket) { + return bucket[agg.id] && bucket[agg.id].location; }, - { - getInternalStartServices, - } - ); + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/geo_centroid_fn.ts b/src/plugins/data/public/search/aggs/metrics/geo_centroid_fn.ts index 464f9b535cd8b..98bd7365f8b3f 100644 --- a/src/plugins/data/public/search/aggs/metrics/geo_centroid_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/geo_centroid_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/max.ts b/src/plugins/data/public/search/aggs/metrics/max.ts index 49cbfba5a269d..5b2f08c5b0260 100644 --- a/src/plugins/data/public/search/aggs/metrics/max.ts +++ b/src/plugins/data/public/search/aggs/metrics/max.ts @@ -21,7 +21,6 @@ import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; const maxTitle = i18n.translate('data.search.aggs.metrics.maxTitle', { @@ -32,31 +31,22 @@ export interface AggParamsMax extends BaseAggParams { field: string; } -export interface MaxMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - -export const getMaxMetricAgg = ({ getInternalStartServices }: MaxMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.MAX, - title: maxTitle, - makeLabel(aggConfig) { - return i18n.translate('data.search.aggs.metrics.maxLabel', { - defaultMessage: 'Max {field}', - values: { field: aggConfig.getFieldDisplayName() }, - }); - }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.DATE], - }, - ], +export const getMaxMetricAgg = () => { + return new MetricAggType({ + name: METRIC_TYPES.MAX, + title: maxTitle, + makeLabel(aggConfig) { + return i18n.translate('data.search.aggs.metrics.maxLabel', { + defaultMessage: 'Max {field}', + values: { field: aggConfig.getFieldDisplayName() }, + }); }, - { - getInternalStartServices, - } - ); + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.DATE], + }, + ], + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/max_fn.ts b/src/plugins/data/public/search/aggs/metrics/max_fn.ts index 1d68c8919fca8..d1bccd08982f8 100644 --- a/src/plugins/data/public/search/aggs/metrics/max_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/max_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/median.test.ts b/src/plugins/data/public/search/aggs/metrics/median.test.ts index b3721e2c1e679..22d907330e2a3 100644 --- a/src/plugins/data/public/search/aggs/metrics/median.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/median.test.ts @@ -17,26 +17,16 @@ * under the License. */ -import { getMedianMetricAgg, MedianMetricAggDependencies } from './median'; +import { getMedianMetricAgg } from './median'; import { AggConfigs, IAggConfigs } from '../agg_configs'; import { mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; -import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; -import { InternalStartServices } from '../../../types'; describe('AggTypeMetricMedianProvider class', () => { let aggConfigs: IAggConfigs; - const aggTypesDependencies: MedianMetricAggDependencies = { - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; beforeEach(() => { - const typesRegistry = mockAggTypesRegistry([getMedianMetricAgg(aggTypesDependencies)]); + const typesRegistry = mockAggTypesRegistry([getMedianMetricAgg()]); const field = { name: 'bytes', }; diff --git a/src/plugins/data/public/search/aggs/metrics/median.ts b/src/plugins/data/public/search/aggs/metrics/median.ts index 725fdcb2400d1..7b48a664b5fb9 100644 --- a/src/plugins/data/public/search/aggs/metrics/median.ts +++ b/src/plugins/data/public/search/aggs/metrics/median.ts @@ -21,7 +21,6 @@ import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; const medianTitle = i18n.translate('data.search.aggs.metrics.medianTitle', { @@ -32,43 +31,30 @@ export interface AggParamsMedian extends BaseAggParams { field: string; } -export interface MedianMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - -export const getMedianMetricAgg = ({ getInternalStartServices }: MedianMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.MEDIAN, - dslName: 'percentiles', - title: medianTitle, - makeLabel(aggConfig) { - return i18n.translate('data.search.aggs.metrics.medianLabel', { - defaultMessage: 'Median {field}', - values: { field: aggConfig.getFieldDisplayName() }, - }); - }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: [ - KBN_FIELD_TYPES.NUMBER, - KBN_FIELD_TYPES.DATE, - KBN_FIELD_TYPES.HISTOGRAM, - ], - write(agg, output) { - output.params.field = agg.getParam('field').name; - output.params.percents = [50]; - }, +export const getMedianMetricAgg = () => { + return new MetricAggType({ + name: METRIC_TYPES.MEDIAN, + dslName: 'percentiles', + title: medianTitle, + makeLabel(aggConfig) { + return i18n.translate('data.search.aggs.metrics.medianLabel', { + defaultMessage: 'Median {field}', + values: { field: aggConfig.getFieldDisplayName() }, + }); + }, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.DATE, KBN_FIELD_TYPES.HISTOGRAM], + write(agg, output) { + output.params.field = agg.getParam('field').name; + output.params.percents = [50]; }, - ], - getValue(agg, bucket) { - return bucket[agg.id].values['50.0']; }, + ], + getValue(agg, bucket) { + return bucket[agg.id].values['50.0']; }, - { - getInternalStartServices, - } - ); + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/median_fn.ts b/src/plugins/data/public/search/aggs/metrics/median_fn.ts index 2e8e89992136e..c5e9edb86e81c 100644 --- a/src/plugins/data/public/search/aggs/metrics/median_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/median_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts b/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts index 5c4ff91258fb0..23dfd976aa846 100644 --- a/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts +++ b/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts @@ -23,7 +23,6 @@ import { AggParamType } from '../param_types/agg'; import { AggConfig } from '../agg_config'; import { METRIC_TYPES } from './metric_agg_types'; import { FieldTypes } from '../param_types'; -import { GetInternalStartServicesFn } from '../../../types'; export interface IMetricAggConfig extends AggConfig { type: InstanceType; @@ -43,10 +42,6 @@ interface MetricAggTypeConfig subtype?: string; } -interface MetricAggTypeDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - // TODO need to make a more explicit interface for this export type IMetricAggType = MetricAggType; @@ -60,11 +55,8 @@ export class MetricAggType {}; - constructor( - config: MetricAggTypeConfig, - dependencies: MetricAggTypeDependencies - ) { - super(config, dependencies); + constructor(config: MetricAggTypeConfig) { + super(config); this.getValue = config.getValue || diff --git a/src/plugins/data/public/search/aggs/metrics/min.ts b/src/plugins/data/public/search/aggs/metrics/min.ts index 0f52aa8a4f788..6472c3ae12990 100644 --- a/src/plugins/data/public/search/aggs/metrics/min.ts +++ b/src/plugins/data/public/search/aggs/metrics/min.ts @@ -21,7 +21,6 @@ import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; const minTitle = i18n.translate('data.search.aggs.metrics.minTitle', { @@ -32,31 +31,22 @@ export interface AggParamsMin extends BaseAggParams { field: string; } -export interface MinMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - -export const getMinMetricAgg = ({ getInternalStartServices }: MinMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.MIN, - title: minTitle, - makeLabel(aggConfig) { - return i18n.translate('data.search.aggs.metrics.minLabel', { - defaultMessage: 'Min {field}', - values: { field: aggConfig.getFieldDisplayName() }, - }); - }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.DATE], - }, - ], +export const getMinMetricAgg = () => { + return new MetricAggType({ + name: METRIC_TYPES.MIN, + title: minTitle, + makeLabel(aggConfig) { + return i18n.translate('data.search.aggs.metrics.minLabel', { + defaultMessage: 'Min {field}', + values: { field: aggConfig.getFieldDisplayName() }, + }); }, - { - getInternalStartServices, - } - ); + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.DATE], + }, + ], + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/min_fn.ts b/src/plugins/data/public/search/aggs/metrics/min_fn.ts index b51da46a137b0..7a57c79a350fa 100644 --- a/src/plugins/data/public/search/aggs/metrics/min_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/min_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/moving_avg.ts b/src/plugins/data/public/search/aggs/metrics/moving_avg.ts index 61384ef1dc106..1791d49b98437 100644 --- a/src/plugins/data/public/search/aggs/metrics/moving_avg.ts +++ b/src/plugins/data/public/search/aggs/metrics/moving_avg.ts @@ -23,7 +23,6 @@ import { parentPipelineAggHelper } from './lib/parent_pipeline_agg_helper'; import { makeNestedLabel } from './lib/make_nested_label'; import { METRIC_TYPES } from './metric_agg_types'; import { AggConfigSerialized, BaseAggParams } from '../types'; -import { GetInternalStartServicesFn } from '../../../types'; export interface AggParamsMovingAvg extends BaseAggParams { buckets_path: string; @@ -33,10 +32,6 @@ export interface AggParamsMovingAvg extends BaseAggParams { metricAgg?: string; } -export interface MovingAvgMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const movingAvgTitle = i18n.translate('data.search.aggs.metrics.movingAvgTitle', { defaultMessage: 'Moving Avg', }); @@ -45,45 +40,38 @@ const movingAvgLabel = i18n.translate('data.search.aggs.metrics.movingAvgLabel', defaultMessage: 'moving avg', }); -export const getMovingAvgMetricAgg = ({ - getInternalStartServices, -}: MovingAvgMetricAggDependencies) => { +export const getMovingAvgMetricAgg = () => { const { subtype, params, getSerializedFormat } = parentPipelineAggHelper; - return new MetricAggType( - { - name: METRIC_TYPES.MOVING_FN, - dslName: 'moving_fn', - title: movingAvgTitle, - makeLabel: (agg) => makeNestedLabel(agg, movingAvgLabel), - subtype, - getSerializedFormat, - params: [ - ...params(), - { - name: 'window', - default: 5, - }, - { - name: 'script', - default: 'MovingFunctions.unweightedAvg(values)', - }, - ], - getValue(agg, bucket) { - /** - * The previous implementation using `moving_avg` did not - * return any bucket in case there are no documents or empty window. - * The `moving_fn` aggregation returns buckets with the value null if the - * window is empty or doesn't return any value if the sibiling metric - * is null. Since our generic MetricAggType.getValue implementation - * would return the value 0 for null buckets, we need a specific - * implementation here, that preserves the null value. - */ - return bucket[agg.id] ? bucket[agg.id].value : null; + return new MetricAggType({ + name: METRIC_TYPES.MOVING_FN, + dslName: 'moving_fn', + title: movingAvgTitle, + makeLabel: (agg) => makeNestedLabel(agg, movingAvgLabel), + subtype, + getSerializedFormat, + params: [ + ...params(), + { + name: 'window', + default: 5, + }, + { + name: 'script', + default: 'MovingFunctions.unweightedAvg(values)', }, + ], + getValue(agg, bucket) { + /** + * The previous implementation using `moving_avg` did not + * return any bucket in case there are no documents or empty window. + * The `moving_fn` aggregation returns buckets with the value null if the + * window is empty or doesn't return any value if the sibiling metric + * is null. Since our generic MetricAggType.getValue implementation + * would return the value 0 for null buckets, we need a specific + * implementation here, that preserves the null value. + */ + return bucket[agg.id] ? bucket[agg.id].value : null; }, - { - getInternalStartServices, - } - ); + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/moving_avg_fn.ts b/src/plugins/data/public/search/aggs/metrics/moving_avg_fn.ts index 54a3fa176385b..e1c1637d3ad1d 100644 --- a/src/plugins/data/public/search/aggs/metrics/moving_avg_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/moving_avg_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts b/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts index 91149a3f29f94..c6bba56f73ec7 100644 --- a/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts @@ -24,38 +24,31 @@ import { getSerialDiffMetricAgg } from './serial_diff'; import { AggConfigs } from '../agg_configs'; import { mockAggTypesRegistry } from '../test_helpers'; import { IMetricAggConfig, MetricAggType } from './metric_agg_type'; -import { GetInternalStartServicesFn, InternalStartServices } from '../../../types'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; describe('parent pipeline aggs', function () { - const getInternalStartServices: GetInternalStartServicesFn = () => - (({ - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices); - const typesRegistry = mockAggTypesRegistry(); const metrics = [ { name: 'derivative', title: 'Derivative', - provider: getDerivativeMetricAgg({ getInternalStartServices }), + provider: getDerivativeMetricAgg(), }, { name: 'cumulative_sum', title: 'Cumulative Sum', - provider: getCumulativeSumMetricAgg({ getInternalStartServices }), + provider: getCumulativeSumMetricAgg(), }, { name: 'moving_avg', title: 'Moving Avg', - provider: getMovingAvgMetricAgg({ getInternalStartServices }), + provider: getMovingAvgMetricAgg(), dslName: 'moving_fn', }, { name: 'serial_diff', title: 'Serial Diff', - provider: getSerialDiffMetricAgg({ getInternalStartServices }), + provider: getSerialDiffMetricAgg(), }, ]; diff --git a/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts b/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts index 39e371763ed4b..348aecc23243a 100644 --- a/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts @@ -27,7 +27,6 @@ import { mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; import { FieldFormatsStart } from '../../../field_formats'; import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; import { InternalStartServices } from '../../../types'; describe('AggTypesMetricsPercentileRanksProvider class', function () { @@ -44,7 +43,6 @@ describe('AggTypesMetricsPercentileRanksProvider class', function () { getInternalStartServices: () => (({ fieldFormats, - notifications: notificationServiceMock.createStartContract(), } as unknown) as InternalStartServices), }; const typesRegistry = mockAggTypesRegistry([getPercentileRanksMetricAgg(aggTypesDependencies)]); diff --git a/src/plugins/data/public/search/aggs/metrics/percentile_ranks.ts b/src/plugins/data/public/search/aggs/metrics/percentile_ranks.ts index 1953c81a99874..3c0be229f1bbd 100644 --- a/src/plugins/data/public/search/aggs/metrics/percentile_ranks.ts +++ b/src/plugins/data/public/search/aggs/metrics/percentile_ranks.ts @@ -59,54 +59,49 @@ const getValueProps = (getInternalStartServices: GetInternalStartServicesFn) => export const getPercentileRanksMetricAgg = ({ getInternalStartServices, }: PercentileRanksMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.PERCENTILE_RANKS, - title: i18n.translate('data.search.aggs.metrics.percentileRanksTitle', { - defaultMessage: 'Percentile Ranks', - }), - makeLabel(agg) { - return i18n.translate('data.search.aggs.metrics.percentileRanksLabel', { - defaultMessage: 'Percentile ranks of {field}', - values: { field: agg.getFieldDisplayName() }, - }); - }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.HISTOGRAM], - }, - { - name: 'values', - default: [], - }, - { - write(agg, output) { - output.params.keyed = false; - }, - }, - ], - getResponseAggs(agg) { - const ValueAggConfig = getResponseAggConfigClass( - agg, - getValueProps(getInternalStartServices) - ); - const values = agg.getParam('values'); - - return values.map((value: any) => new ValueAggConfig(value)); + return new MetricAggType({ + name: METRIC_TYPES.PERCENTILE_RANKS, + title: i18n.translate('data.search.aggs.metrics.percentileRanksTitle', { + defaultMessage: 'Percentile Ranks', + }), + makeLabel(agg) { + return i18n.translate('data.search.aggs.metrics.percentileRanksLabel', { + defaultMessage: 'Percentile ranks of {field}', + values: { field: agg.getFieldDisplayName() }, + }); + }, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.HISTOGRAM], }, - getSerializedFormat(agg) { - return { - id: 'percent', - }; + { + name: 'values', + default: [], }, - getValue(agg, bucket) { - return getPercentileValue(agg, bucket) / 100; + { + write(agg, output) { + output.params.keyed = false; + }, }, + ], + getResponseAggs(agg) { + const ValueAggConfig = getResponseAggConfigClass( + agg, + getValueProps(getInternalStartServices) + ); + const values = agg.getParam('values'); + + return values.map((value: any) => new ValueAggConfig(value)); + }, + getSerializedFormat(agg) { + return { + id: 'percent', + }; + }, + getValue(agg, bucket) { + return getPercentileValue(agg, bucket) / 100; }, - { - getInternalStartServices, - } - ); + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/percentile_ranks_fn.ts b/src/plugins/data/public/search/aggs/metrics/percentile_ranks_fn.ts index 851e938f28c1c..08e1489a856dd 100644 --- a/src/plugins/data/public/search/aggs/metrics/percentile_ranks_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/percentile_ranks_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/percentiles.test.ts b/src/plugins/data/public/search/aggs/metrics/percentiles.test.ts index 52ab325ac5806..a44c0e5075ef9 100644 --- a/src/plugins/data/public/search/aggs/metrics/percentiles.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/percentiles.test.ts @@ -17,30 +17,16 @@ * under the License. */ -import { - IPercentileAggConfig, - getPercentilesMetricAgg, - PercentilesMetricAggDependencies, -} from './percentiles'; +import { IPercentileAggConfig, getPercentilesMetricAgg } from './percentiles'; import { AggConfigs, IAggConfigs } from '../agg_configs'; import { mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; -import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; -import { InternalStartServices } from '../../../types'; describe('AggTypesMetricsPercentilesProvider class', () => { let aggConfigs: IAggConfigs; - const aggTypesDependencies: PercentilesMetricAggDependencies = { - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; beforeEach(() => { - const typesRegistry = mockAggTypesRegistry([getPercentilesMetricAgg(aggTypesDependencies)]); + const typesRegistry = mockAggTypesRegistry([getPercentilesMetricAgg()]); const field = { name: 'bytes', }; @@ -72,7 +58,7 @@ describe('AggTypesMetricsPercentilesProvider class', () => { }); it('uses the custom label if it is set', () => { - const responseAggs: any = getPercentilesMetricAgg(aggTypesDependencies).getResponseAggs( + const responseAggs: any = getPercentilesMetricAgg().getResponseAggs( aggConfigs.aggs[0] as IPercentileAggConfig ); diff --git a/src/plugins/data/public/search/aggs/metrics/percentiles.ts b/src/plugins/data/public/search/aggs/metrics/percentiles.ts index ad3c19cfaffcc..8ea493f324811 100644 --- a/src/plugins/data/public/search/aggs/metrics/percentiles.ts +++ b/src/plugins/data/public/search/aggs/metrics/percentiles.ts @@ -24,7 +24,6 @@ import { KBN_FIELD_TYPES } from '../../../../common'; import { getResponseAggConfigClass, IResponseAggConfig } from './lib/get_response_agg_config_class'; import { getPercentileValue } from './percentiles_get_value'; import { ordinalSuffix } from './lib/ordinal_suffix'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; export interface AggParamsPercentiles extends BaseAggParams { @@ -34,10 +33,6 @@ export interface AggParamsPercentiles extends BaseAggParams { export type IPercentileAggConfig = IResponseAggConfig; -export interface PercentilesMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const valueProps = { makeLabel(this: IPercentileAggConfig) { const customLabel = this.getParam('customLabel'); @@ -50,51 +45,40 @@ const valueProps = { }, }; -export const getPercentilesMetricAgg = ({ - getInternalStartServices, -}: PercentilesMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.PERCENTILES, - title: i18n.translate('data.search.aggs.metrics.percentilesTitle', { - defaultMessage: 'Percentiles', - }), - makeLabel(agg) { - return i18n.translate('data.search.aggs.metrics.percentilesLabel', { - defaultMessage: 'Percentiles of {field}', - values: { field: agg.getFieldDisplayName() }, - }); +export const getPercentilesMetricAgg = () => { + return new MetricAggType({ + name: METRIC_TYPES.PERCENTILES, + title: i18n.translate('data.search.aggs.metrics.percentilesTitle', { + defaultMessage: 'Percentiles', + }), + makeLabel(agg) { + return i18n.translate('data.search.aggs.metrics.percentilesLabel', { + defaultMessage: 'Percentiles of {field}', + values: { field: agg.getFieldDisplayName() }, + }); + }, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.DATE, KBN_FIELD_TYPES.HISTOGRAM], }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: [ - KBN_FIELD_TYPES.NUMBER, - KBN_FIELD_TYPES.DATE, - KBN_FIELD_TYPES.HISTOGRAM, - ], - }, - { - name: 'percents', - default: [1, 5, 25, 50, 75, 95, 99], - }, - { - write(agg, output) { - output.params.keyed = false; - }, + { + name: 'percents', + default: [1, 5, 25, 50, 75, 95, 99], + }, + { + write(agg, output) { + output.params.keyed = false; }, - ], - getResponseAggs(agg) { - const ValueAggConfig = getResponseAggConfigClass(agg, valueProps); - - return agg.getParam('percents').map((percent: any) => new ValueAggConfig(percent)); }, + ], + getResponseAggs(agg) { + const ValueAggConfig = getResponseAggConfigClass(agg, valueProps); - getValue: getPercentileValue, + return agg.getParam('percents').map((percent: any) => new ValueAggConfig(percent)); }, - { - getInternalStartServices, - } - ); + + getValue: getPercentileValue, + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/percentiles_fn.ts b/src/plugins/data/public/search/aggs/metrics/percentiles_fn.ts index b799be07925fa..eb8952267f5ea 100644 --- a/src/plugins/data/public/search/aggs/metrics/percentiles_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/percentiles_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/serial_diff.ts b/src/plugins/data/public/search/aggs/metrics/serial_diff.ts index 9ea01be11fe8f..a4e4d7a8990fa 100644 --- a/src/plugins/data/public/search/aggs/metrics/serial_diff.ts +++ b/src/plugins/data/public/search/aggs/metrics/serial_diff.ts @@ -23,7 +23,6 @@ import { parentPipelineAggHelper } from './lib/parent_pipeline_agg_helper'; import { makeNestedLabel } from './lib/make_nested_label'; import { METRIC_TYPES } from './metric_agg_types'; import { AggConfigSerialized, BaseAggParams } from '../types'; -import { GetInternalStartServicesFn } from '../../../types'; export interface AggParamsSerialDiff extends BaseAggParams { buckets_path: string; @@ -31,10 +30,6 @@ export interface AggParamsSerialDiff extends BaseAggParams { metricAgg?: string; } -export interface SerialDiffMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const serialDiffTitle = i18n.translate('data.search.aggs.metrics.serialDiffTitle', { defaultMessage: 'Serial Diff', }); @@ -43,22 +38,15 @@ const serialDiffLabel = i18n.translate('data.search.aggs.metrics.serialDiffLabel defaultMessage: 'serial diff', }); -export const getSerialDiffMetricAgg = ({ - getInternalStartServices, -}: SerialDiffMetricAggDependencies) => { +export const getSerialDiffMetricAgg = () => { const { subtype, params, getSerializedFormat } = parentPipelineAggHelper; - return new MetricAggType( - { - name: METRIC_TYPES.SERIAL_DIFF, - title: serialDiffTitle, - makeLabel: (agg) => makeNestedLabel(agg, serialDiffLabel), - subtype, - params: [...params()], - getSerializedFormat, - }, - { - getInternalStartServices, - } - ); + return new MetricAggType({ + name: METRIC_TYPES.SERIAL_DIFF, + title: serialDiffTitle, + makeLabel: (agg) => makeNestedLabel(agg, serialDiffLabel), + subtype, + params: [...params()], + getSerializedFormat, + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/serial_diff_fn.ts b/src/plugins/data/public/search/aggs/metrics/serial_diff_fn.ts index 9ba313aff7386..3cc1dacb87b3d 100644 --- a/src/plugins/data/public/search/aggs/metrics/serial_diff_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/serial_diff_fn.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts b/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts index f08e850caadce..a157d225c839c 100644 --- a/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts @@ -25,37 +25,30 @@ import { getBucketMaxMetricAgg } from './bucket_max'; import { AggConfigs } from '../agg_configs'; import { IMetricAggConfig, MetricAggType } from './metric_agg_type'; import { mockAggTypesRegistry } from '../test_helpers'; -import { GetInternalStartServicesFn, InternalStartServices } from '../../../types'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; describe('sibling pipeline aggs', () => { - const getInternalStartServices: GetInternalStartServicesFn = () => - (({ - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices); - const typesRegistry = mockAggTypesRegistry(); const metrics = [ { name: 'sum_bucket', title: 'Overall Sum', - provider: getBucketSumMetricAgg({ getInternalStartServices }), + provider: getBucketSumMetricAgg(), }, { name: 'avg_bucket', title: 'Overall Average', - provider: getBucketAvgMetricAgg({ getInternalStartServices }), + provider: getBucketAvgMetricAgg(), }, { name: 'min_bucket', title: 'Overall Min', - provider: getBucketMinMetricAgg({ getInternalStartServices }), + provider: getBucketMinMetricAgg(), }, { name: 'max_bucket', title: 'Overall Max', - provider: getBucketMaxMetricAgg({ getInternalStartServices }), + provider: getBucketMaxMetricAgg(), }, ]; diff --git a/src/plugins/data/public/search/aggs/metrics/std_deviation.test.ts b/src/plugins/data/public/search/aggs/metrics/std_deviation.test.ts index 2fa207e62771e..c3efe95f44a56 100644 --- a/src/plugins/data/public/search/aggs/metrics/std_deviation.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/std_deviation.test.ts @@ -17,27 +17,13 @@ * under the License. */ -import { - IStdDevAggConfig, - getStdDeviationMetricAgg, - StdDeviationMetricAggDependencies, -} from './std_deviation'; +import { IStdDevAggConfig, getStdDeviationMetricAgg } from './std_deviation'; import { AggConfigs } from '../agg_configs'; import { mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; -import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; -import { InternalStartServices } from '../../../types'; describe('AggTypeMetricStandardDeviationProvider class', () => { - const aggTypesDependencies: StdDeviationMetricAggDependencies = { - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; - const typesRegistry = mockAggTypesRegistry([getStdDeviationMetricAgg(aggTypesDependencies)]); + const typesRegistry = mockAggTypesRegistry([getStdDeviationMetricAgg()]); const getAggConfigs = (customLabel?: string) => { const field = { name: 'memory', @@ -72,7 +58,7 @@ describe('AggTypeMetricStandardDeviationProvider class', () => { it('uses the custom label if it is set', () => { const aggConfigs = getAggConfigs('custom label'); - const responseAggs: any = getStdDeviationMetricAgg(aggTypesDependencies).getResponseAggs( + const responseAggs: any = getStdDeviationMetricAgg().getResponseAggs( aggConfigs.aggs[0] as IStdDevAggConfig ); @@ -86,7 +72,7 @@ describe('AggTypeMetricStandardDeviationProvider class', () => { it('uses the default labels if custom label is not set', () => { const aggConfigs = getAggConfigs(); - const responseAggs: any = getStdDeviationMetricAgg(aggTypesDependencies).getResponseAggs( + const responseAggs: any = getStdDeviationMetricAgg().getResponseAggs( aggConfigs.aggs[0] as IStdDevAggConfig ); diff --git a/src/plugins/data/public/search/aggs/metrics/std_deviation.ts b/src/plugins/data/public/search/aggs/metrics/std_deviation.ts index 5d987dc2cbbe9..9aba063776252 100644 --- a/src/plugins/data/public/search/aggs/metrics/std_deviation.ts +++ b/src/plugins/data/public/search/aggs/metrics/std_deviation.ts @@ -23,7 +23,6 @@ import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { getResponseAggConfigClass, IResponseAggConfig } from './lib/get_response_agg_config_class'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; export interface AggParamsStdDeviation extends BaseAggParams { @@ -36,12 +35,8 @@ interface ValProp { } export interface IStdDevAggConfig extends IResponseAggConfig { - keyedDetails: (customLabel: string, fieldDisplayName?: string) => { [key: string]: ValProp }; - valProp: () => ValProp; -} - -export interface StdDeviationMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; + keyedDetails: (customLabel: string, fieldDisplayName?: string) => Record; + valProp: () => string[]; } const responseAggConfigProps = { @@ -85,42 +80,35 @@ const responseAggConfigProps = { }, }; -export const getStdDeviationMetricAgg = ({ - getInternalStartServices, -}: StdDeviationMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.STD_DEV, - dslName: 'extended_stats', - title: i18n.translate('data.search.aggs.metrics.standardDeviationTitle', { - defaultMessage: 'Standard Deviation', - }), - makeLabel(agg) { - return i18n.translate('data.search.aggs.metrics.standardDeviationLabel', { - defaultMessage: 'Standard Deviation of {field}', - values: { field: agg.getFieldDisplayName() }, - }); +export const getStdDeviationMetricAgg = () => { + return new MetricAggType({ + name: METRIC_TYPES.STD_DEV, + dslName: 'extended_stats', + title: i18n.translate('data.search.aggs.metrics.standardDeviationTitle', { + defaultMessage: 'Standard Deviation', + }), + makeLabel(agg) { + return i18n.translate('data.search.aggs.metrics.standardDeviationLabel', { + defaultMessage: 'Standard Deviation of {field}', + values: { field: agg.getFieldDisplayName() }, + }); + }, + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: KBN_FIELD_TYPES.NUMBER, }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: KBN_FIELD_TYPES.NUMBER, - }, - ], + ], - getResponseAggs(agg) { - const ValueAggConfig = getResponseAggConfigClass(agg, responseAggConfigProps); + getResponseAggs(agg) { + const ValueAggConfig = getResponseAggConfigClass(agg, responseAggConfigProps); - return [new ValueAggConfig('std_lower'), new ValueAggConfig('std_upper')]; - }, + return [new ValueAggConfig('std_lower'), new ValueAggConfig('std_upper')]; + }, - getValue(agg, bucket) { - return get(bucket[agg.parentId], agg.valProp() as any); - }, + getValue(agg, bucket) { + return get(bucket[agg.parentId], agg.valProp()); }, - { - getInternalStartServices, - } - ); + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/std_deviation_fn.ts b/src/plugins/data/public/search/aggs/metrics/std_deviation_fn.ts index 70623e2e48041..61b8a6f28f088 100644 --- a/src/plugins/data/public/search/aggs/metrics/std_deviation_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/std_deviation_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/sum.ts b/src/plugins/data/public/search/aggs/metrics/sum.ts index 66fad89316613..fa44af98554da 100644 --- a/src/plugins/data/public/search/aggs/metrics/sum.ts +++ b/src/plugins/data/public/search/aggs/metrics/sum.ts @@ -21,7 +21,6 @@ import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; const sumTitle = i18n.translate('data.search.aggs.metrics.sumTitle', { @@ -32,34 +31,25 @@ export interface AggParamsSum extends BaseAggParams { field: string; } -export interface SumMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - -export const getSumMetricAgg = ({ getInternalStartServices }: SumMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.SUM, - title: sumTitle, - makeLabel(aggConfig) { - return i18n.translate('data.search.aggs.metrics.sumLabel', { - defaultMessage: 'Sum of {field}', - values: { field: aggConfig.getFieldDisplayName() }, - }); - }, - isScalable() { - return true; - }, - params: [ - { - name: 'field', - type: 'field', - filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.HISTOGRAM], - }, - ], +export const getSumMetricAgg = () => { + return new MetricAggType({ + name: METRIC_TYPES.SUM, + title: sumTitle, + makeLabel(aggConfig) { + return i18n.translate('data.search.aggs.metrics.sumLabel', { + defaultMessage: 'Sum of {field}', + values: { field: aggConfig.getFieldDisplayName() }, + }); + }, + isScalable() { + return true; }, - { - getInternalStartServices, - } - ); + params: [ + { + name: 'field', + type: 'field', + filterFieldTypes: [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.HISTOGRAM], + }, + ], + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/sum_fn.ts b/src/plugins/data/public/search/aggs/metrics/sum_fn.ts index a277aef02693f..e625befc8f1d9 100644 --- a/src/plugins/data/public/search/aggs/metrics/sum_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/sum_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts b/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts index 94a970a72a46f..cd5b4a2f724bd 100644 --- a/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts @@ -18,25 +18,15 @@ */ import { dropRight, last } from 'lodash'; -import { getTopHitMetricAgg, TopHitMetricAggDependencies } from './top_hit'; +import { getTopHitMetricAgg } from './top_hit'; import { AggConfigs } from '../agg_configs'; import { mockAggTypesRegistry } from '../test_helpers'; import { IMetricAggConfig } from './metric_agg_type'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; -import { InternalStartServices } from '../../../types'; describe('Top hit metric', () => { let aggDsl: Record; let aggConfig: IMetricAggConfig; - const aggTypesDependencies: TopHitMetricAggDependencies = { - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; const init = ({ fieldName = 'field', @@ -46,7 +36,7 @@ describe('Top hit metric', () => { fieldType = KBN_FIELD_TYPES.NUMBER, size = 1, }: any) => { - const typesRegistry = mockAggTypesRegistry([getTopHitMetricAgg(aggTypesDependencies)]); + const typesRegistry = mockAggTypesRegistry([getTopHitMetricAgg()]); const field = { name: fieldName, displayName: fieldName, @@ -101,7 +91,7 @@ describe('Top hit metric', () => { it('should return a label prefixed with Last if sorting in descending order', () => { init({ fieldName: 'bytes' }); - expect(getTopHitMetricAgg(aggTypesDependencies).makeLabel(aggConfig)).toEqual('Last bytes'); + expect(getTopHitMetricAgg().makeLabel(aggConfig)).toEqual('Last bytes'); }); it('should return a label prefixed with First if sorting in ascending order', () => { @@ -109,7 +99,7 @@ describe('Top hit metric', () => { fieldName: 'bytes', sortOrder: 'asc', }); - expect(getTopHitMetricAgg(aggTypesDependencies).makeLabel(aggConfig)).toEqual('First bytes'); + expect(getTopHitMetricAgg().makeLabel(aggConfig)).toEqual('First bytes'); }); it('should request the _source field', () => { @@ -150,7 +140,7 @@ describe('Top hit metric', () => { }; init({ fieldName: '@tags' }); - expect(getTopHitMetricAgg(aggTypesDependencies).getValue(aggConfig, bucket)).toBe(null); + expect(getTopHitMetricAgg().getValue(aggConfig, bucket)).toBe(null); }); // it('should return undefined if the field does not appear in the source', () => { @@ -169,7 +159,7 @@ describe('Top hit metric', () => { }; init({ fieldName: '@tags' }); - expect(getTopHitMetricAgg(aggTypesDependencies).getValue(aggConfig, bucket)).toBe(undefined); + expect(getTopHitMetricAgg().getValue(aggConfig, bucket)).toBe(undefined); }); it('should return the field value from the top hit', () => { @@ -188,7 +178,7 @@ describe('Top hit metric', () => { }; init({ fieldName: '@tags' }); - expect(getTopHitMetricAgg(aggTypesDependencies).getValue(aggConfig, bucket)).toBe('aaa'); + expect(getTopHitMetricAgg().getValue(aggConfig, bucket)).toBe('aaa'); }); it('should return the object if the field value is an object', () => { @@ -210,7 +200,7 @@ describe('Top hit metric', () => { init({ fieldName: '@tags' }); - expect(getTopHitMetricAgg(aggTypesDependencies).getValue(aggConfig, bucket)).toEqual({ + expect(getTopHitMetricAgg().getValue(aggConfig, bucket)).toEqual({ label: 'aaa', }); }); @@ -231,10 +221,7 @@ describe('Top hit metric', () => { }; init({ fieldName: '@tags' }); - expect(getTopHitMetricAgg(aggTypesDependencies).getValue(aggConfig, bucket)).toEqual([ - 'aaa', - 'bbb', - ]); + expect(getTopHitMetricAgg().getValue(aggConfig, bucket)).toEqual(['aaa', 'bbb']); }); it('should return undefined if the field is not in the source nor in the doc_values field', () => { @@ -256,7 +243,7 @@ describe('Top hit metric', () => { }; init({ fieldName: 'machine.os.raw', readFromDocValues: true }); - expect(getTopHitMetricAgg(aggTypesDependencies).getValue(aggConfig, bucket)).toBe(undefined); + expect(getTopHitMetricAgg().getValue(aggConfig, bucket)).toBe(undefined); }); describe('Multivalued field and first/last X docs', () => { @@ -265,9 +252,7 @@ describe('Top hit metric', () => { fieldName: 'bytes', size: 2, }); - expect(getTopHitMetricAgg(aggTypesDependencies).makeLabel(aggConfig)).toEqual( - 'Last 2 bytes' - ); + expect(getTopHitMetricAgg().makeLabel(aggConfig)).toEqual('Last 2 bytes'); }); it('should return a label prefixed with First X docs if sorting in ascending order', () => { @@ -276,9 +261,7 @@ describe('Top hit metric', () => { size: 2, sortOrder: 'asc', }); - expect(getTopHitMetricAgg(aggTypesDependencies).makeLabel(aggConfig)).toEqual( - 'First 2 bytes' - ); + expect(getTopHitMetricAgg().makeLabel(aggConfig)).toEqual('First 2 bytes'); }); [ @@ -353,9 +336,7 @@ describe('Top hit metric', () => { }; init({ fieldName: 'bytes', aggregate: agg.type }); - expect(getTopHitMetricAgg(aggTypesDependencies).getValue(aggConfig, bucket)).toEqual( - agg.result - ); + expect(getTopHitMetricAgg().getValue(aggConfig, bucket)).toEqual(agg.result); }); it(`should return the result of the ${agg.type} aggregation over the last X docs - ${agg.description}`, () => { @@ -379,9 +360,7 @@ describe('Top hit metric', () => { }; init({ fieldName: 'bytes', aggregate: agg.type }); - expect(getTopHitMetricAgg(aggTypesDependencies).getValue(aggConfig, bucket)).toEqual( - agg.result - ); + expect(getTopHitMetricAgg().getValue(aggConfig, bucket)).toEqual(agg.result); }); }); }); diff --git a/src/plugins/data/public/search/aggs/metrics/top_hit.ts b/src/plugins/data/public/search/aggs/metrics/top_hit.ts index c6890f98b20e4..5ca883e60afd3 100644 --- a/src/plugins/data/public/search/aggs/metrics/top_hit.ts +++ b/src/plugins/data/public/search/aggs/metrics/top_hit.ts @@ -22,7 +22,6 @@ import { i18n } from '@kbn/i18n'; import { IMetricAggConfig, MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; -import { GetInternalStartServicesFn } from '../../../types'; import { BaseAggParams } from '../types'; export interface AggParamsTopHit extends BaseAggParams { @@ -33,235 +32,223 @@ export interface AggParamsTopHit extends BaseAggParams { sortOrder?: 'desc' | 'asc'; } -export interface TopHitMetricAggDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - const isNumericFieldSelected = (agg: IMetricAggConfig) => { const field = agg.getParam('field'); return field && field.type && field.type === KBN_FIELD_TYPES.NUMBER; }; -export const getTopHitMetricAgg = ({ getInternalStartServices }: TopHitMetricAggDependencies) => { - return new MetricAggType( - { - name: METRIC_TYPES.TOP_HITS, - title: i18n.translate('data.search.aggs.metrics.topHitTitle', { - defaultMessage: 'Top Hit', - }), - makeLabel(aggConfig) { - const lastPrefixLabel = i18n.translate('data.search.aggs.metrics.topHit.lastPrefixLabel', { - defaultMessage: 'Last', - }); - const firstPrefixLabel = i18n.translate( - 'data.search.aggs.metrics.topHit.firstPrefixLabel', - { - defaultMessage: 'First', - } - ); +export const getTopHitMetricAgg = () => { + return new MetricAggType({ + name: METRIC_TYPES.TOP_HITS, + title: i18n.translate('data.search.aggs.metrics.topHitTitle', { + defaultMessage: 'Top Hit', + }), + makeLabel(aggConfig) { + const lastPrefixLabel = i18n.translate('data.search.aggs.metrics.topHit.lastPrefixLabel', { + defaultMessage: 'Last', + }); + const firstPrefixLabel = i18n.translate('data.search.aggs.metrics.topHit.firstPrefixLabel', { + defaultMessage: 'First', + }); - let prefix = - aggConfig.getParam('sortOrder').value === 'desc' ? lastPrefixLabel : firstPrefixLabel; + let prefix = + aggConfig.getParam('sortOrder').value === 'desc' ? lastPrefixLabel : firstPrefixLabel; - const size = aggConfig.getParam('size'); + const size = aggConfig.getParam('size'); - if (size !== 1) { - prefix += ` ${size}`; - } - - const field = aggConfig.getParam('field'); + if (size !== 1) { + prefix += ` ${size}`; + } - return `${prefix} ${field ? field.displayName : ''}`; - }, - params: [ - { - name: 'field', - type: 'field', - onlyAggregatable: false, - filterFieldTypes: Object.values(KBN_FIELD_TYPES).filter( - (type) => type !== KBN_FIELD_TYPES.HISTOGRAM - ), - write(agg, output) { - const field = agg.getParam('field'); - output.params = {}; + const field = aggConfig.getParam('field'); - if (field.scripted) { - output.params.script_fields = { - [field.name]: { - script: { - source: field.script, - lang: field.lang, - }, + return `${prefix} ${field ? field.displayName : ''}`; + }, + params: [ + { + name: 'field', + type: 'field', + onlyAggregatable: false, + filterFieldTypes: Object.values(KBN_FIELD_TYPES).filter( + (type) => type !== KBN_FIELD_TYPES.HISTOGRAM + ), + write(agg, output) { + const field = agg.getParam('field'); + output.params = {}; + + if (field.scripted) { + output.params.script_fields = { + [field.name]: { + script: { + source: field.script, + lang: field.lang, }, - }; - } else { - if (field.readFromDocValues) { - // always format date fields as date_time to avoid - // displaying unformatted dates like epoch_millis - // or other not-accepted momentjs formats - const format = - field.type === KBN_FIELD_TYPES.DATE ? 'date_time' : 'use_field_mapping'; - output.params.docvalue_fields = [{ field: field.name, format }]; - } - output.params._source = field.name === '_source' ? true : field.name; + }, + }; + } else { + if (field.readFromDocValues) { + // always format date fields as date_time to avoid + // displaying unformatted dates like epoch_millis + // or other not-accepted momentjs formats + const format = + field.type === KBN_FIELD_TYPES.DATE ? 'date_time' : 'use_field_mapping'; + output.params.docvalue_fields = [{ field: field.name, format }]; } - }, + output.params._source = field.name === '_source' ? true : field.name; + } }, - { - name: 'aggregate', - type: 'optioned', - options: [ - { - text: i18n.translate('data.search.aggs.metrics.topHit.minLabel', { - defaultMessage: 'Min', - }), - isCompatible: isNumericFieldSelected, - disabled: true, - value: 'min', - }, - { - text: i18n.translate('data.search.aggs.metrics.topHit.maxLabel', { - defaultMessage: 'Max', - }), - isCompatible: isNumericFieldSelected, - disabled: true, - value: 'max', - }, - { - text: i18n.translate('data.search.aggs.metrics.topHit.sumLabel', { - defaultMessage: 'Sum', - }), - isCompatible: isNumericFieldSelected, - disabled: true, - value: 'sum', - }, - { - text: i18n.translate('data.search.aggs.metrics.topHit.averageLabel', { - defaultMessage: 'Average', - }), - isCompatible: isNumericFieldSelected, - disabled: true, - value: 'average', - }, - { - text: i18n.translate('data.search.aggs.metrics.topHit.concatenateLabel', { - defaultMessage: 'Concatenate', - }), - isCompatible(aggConfig: IMetricAggConfig) { - return _.get(aggConfig.params, 'field.filterFieldTypes', '*') === '*'; - }, - disabled: true, - value: 'concat', + }, + { + name: 'aggregate', + type: 'optioned', + options: [ + { + text: i18n.translate('data.search.aggs.metrics.topHit.minLabel', { + defaultMessage: 'Min', + }), + isCompatible: isNumericFieldSelected, + disabled: true, + value: 'min', + }, + { + text: i18n.translate('data.search.aggs.metrics.topHit.maxLabel', { + defaultMessage: 'Max', + }), + isCompatible: isNumericFieldSelected, + disabled: true, + value: 'max', + }, + { + text: i18n.translate('data.search.aggs.metrics.topHit.sumLabel', { + defaultMessage: 'Sum', + }), + isCompatible: isNumericFieldSelected, + disabled: true, + value: 'sum', + }, + { + text: i18n.translate('data.search.aggs.metrics.topHit.averageLabel', { + defaultMessage: 'Average', + }), + isCompatible: isNumericFieldSelected, + disabled: true, + value: 'average', + }, + { + text: i18n.translate('data.search.aggs.metrics.topHit.concatenateLabel', { + defaultMessage: 'Concatenate', + }), + isCompatible(aggConfig: IMetricAggConfig) { + return _.get(aggConfig.params, 'field.filterFieldTypes', '*') === '*'; }, - ], - write: _.noop, - }, - { - name: 'size', - default: 1, - }, - { - name: 'sortField', - type: 'field', - filterFieldTypes: [ - KBN_FIELD_TYPES.NUMBER, - KBN_FIELD_TYPES.DATE, - KBN_FIELD_TYPES.IP, - KBN_FIELD_TYPES.STRING, - ], - default(agg: IMetricAggConfig) { - return agg.getIndexPattern().timeFieldName; + disabled: true, + value: 'concat', }, - write: _.noop, // prevent default write, it is handled below + ], + write: _.noop, + }, + { + name: 'size', + default: 1, + }, + { + name: 'sortField', + type: 'field', + filterFieldTypes: [ + KBN_FIELD_TYPES.NUMBER, + KBN_FIELD_TYPES.DATE, + KBN_FIELD_TYPES.IP, + KBN_FIELD_TYPES.STRING, + ], + default(agg: IMetricAggConfig) { + return agg.getIndexPattern().timeFieldName; }, - { - name: 'sortOrder', - type: 'optioned', - default: 'desc', - options: [ - { - text: i18n.translate('data.search.aggs.metrics.topHit.descendingLabel', { - defaultMessage: 'Descending', - }), - value: 'desc', - }, - { - text: i18n.translate('data.search.aggs.metrics.topHit.ascendingLabel', { - defaultMessage: 'Ascending', - }), - value: 'asc', - }, - ], - write(agg, output) { - const sortField = agg.params.sortField; - const sortOrder = agg.params.sortOrder; - - if (sortField.scripted) { - output.params.sort = [ - { - _script: { - script: { - source: sortField.script, - lang: sortField.lang, - }, - type: sortField.type, - order: sortOrder.value, + write: _.noop, // prevent default write, it is handled below + }, + { + name: 'sortOrder', + type: 'optioned', + default: 'desc', + options: [ + { + text: i18n.translate('data.search.aggs.metrics.topHit.descendingLabel', { + defaultMessage: 'Descending', + }), + value: 'desc', + }, + { + text: i18n.translate('data.search.aggs.metrics.topHit.ascendingLabel', { + defaultMessage: 'Ascending', + }), + value: 'asc', + }, + ], + write(agg, output) { + const sortField = agg.params.sortField; + const sortOrder = agg.params.sortOrder; + + if (sortField.scripted) { + output.params.sort = [ + { + _script: { + script: { + source: sortField.script, + lang: sortField.lang, }, + type: sortField.type, + order: sortOrder.value, }, - ]; - } else { - output.params.sort = [ - { - [sortField.name]: { - order: sortOrder.value, - }, + }, + ]; + } else { + output.params.sort = [ + { + [sortField.name]: { + order: sortOrder.value, }, - ]; - } - }, + }, + ]; + } }, - ], - getValue(agg, bucket) { - const hits: any[] = _.get(bucket, `${agg.id}.hits.hits`); - if (!hits || !hits.length) { + }, + ], + getValue(agg, bucket) { + const hits: any[] = _.get(bucket, `${agg.id}.hits.hits`); + if (!hits || !hits.length) { + return null; + } + const path = agg.getParam('field').name; + + let values = _.flatten( + hits.map((hit) => + path === '_source' ? hit._source : agg.getIndexPattern().flattenHit(hit, true)[path] + ) + ); + + if (values.length === 1) { + values = values[0]; + } + + if (Array.isArray(values)) { + if (!_.compact(values).length) { return null; } - const path = agg.getParam('field').name; - - let values = _.flatten( - hits.map((hit) => - path === '_source' ? hit._source : agg.getIndexPattern().flattenHit(hit, true)[path] - ) - ); - - if (values.length === 1) { - values = values[0]; - } - - if (Array.isArray(values)) { - if (!_.compact(values).length) { - return null; - } - const aggregate = agg.getParam('aggregate'); - - switch (aggregate.value) { - case 'max': - return _.max(values); - case 'min': - return _.min(values); - case 'sum': - return _.sum(values); - case 'average': - return _.sum(values) / values.length; - } + const aggregate = agg.getParam('aggregate'); + + switch (aggregate.value) { + case 'max': + return _.max(values); + case 'min': + return _.min(values); + case 'sum': + return _.sum(values); + case 'average': + return _.sum(values) / values.length; } - return values; - }, + } + return values; }, - { - getInternalStartServices, - } - ); + }); }; diff --git a/src/plugins/data/public/search/aggs/metrics/top_hit_fn.ts b/src/plugins/data/public/search/aggs/metrics/top_hit_fn.ts index adfd22b540e06..e0c3fd0d070b2 100644 --- a/src/plugins/data/public/search/aggs/metrics/top_hit_fn.ts +++ b/src/plugins/data/public/search/aggs/metrics/top_hit_fn.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { AggExpressionType, AggExpressionFunctionArgs, METRIC_TYPES } from '../'; import { getParsedValue } from '../utils/get_parsed_value'; diff --git a/src/plugins/data/public/search/aggs/param_types/base.ts b/src/plugins/data/public/search/aggs/param_types/base.ts index 79e1cf2a540d1..1ba8a75e98cbe 100644 --- a/src/plugins/data/public/search/aggs/param_types/base.ts +++ b/src/plugins/data/public/search/aggs/param_types/base.ts @@ -17,7 +17,7 @@ * under the License. */ -import { ExpressionAstFunction } from 'src/plugins/expressions/public'; +import { ExpressionAstFunction } from 'src/plugins/expressions/common'; import { IAggConfigs } from '../agg_configs'; import { IAggConfig } from '../agg_config'; import { FetchOptions } from '../../fetch'; diff --git a/src/plugins/data/public/search/aggs/param_types/field.test.ts b/src/plugins/data/public/search/aggs/param_types/field.test.ts index 2c51d9709f906..0182471392910 100644 --- a/src/plugins/data/public/search/aggs/param_types/field.test.ts +++ b/src/plugins/data/public/search/aggs/param_types/field.test.ts @@ -18,22 +18,11 @@ */ import { BaseParamType } from './base'; -import { FieldParamType, FieldParamTypeDependencies } from './field'; +import { FieldParamType } from './field'; import { ES_FIELD_TYPES, KBN_FIELD_TYPES } from '../../../../common'; import { IAggConfig } from '../agg_config'; -import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; -import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; -import { InternalStartServices } from '../../../types'; describe('Field', () => { - const fieldParamTypeDependencies: FieldParamTypeDependencies = { - getInternalStartServices: () => - (({ - fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - } as unknown) as InternalStartServices), - }; - const indexPattern = { id: '1234', title: 'logstash-*', @@ -63,13 +52,10 @@ describe('Field', () => { describe('constructor', () => { it('it is an instance of BaseParamType', () => { - const aggParam = new FieldParamType( - { - name: 'field', - type: 'field', - }, - fieldParamTypeDependencies - ); + const aggParam = new FieldParamType({ + name: 'field', + type: 'field', + }); expect(aggParam instanceof BaseParamType).toBeTruthy(); }); @@ -77,13 +63,10 @@ describe('Field', () => { describe('getAvailableFields', () => { it('should return only aggregatable fields by default', () => { - const aggParam = new FieldParamType( - { - name: 'field', - type: 'field', - }, - fieldParamTypeDependencies - ); + const aggParam = new FieldParamType({ + name: 'field', + type: 'field', + }); const fields = aggParam.getAvailableFields(agg); @@ -95,13 +78,10 @@ describe('Field', () => { }); it('should return all fields if onlyAggregatable is false', () => { - const aggParam = new FieldParamType( - { - name: 'field', - type: 'field', - }, - fieldParamTypeDependencies - ); + const aggParam = new FieldParamType({ + name: 'field', + type: 'field', + }); aggParam.onlyAggregatable = false; @@ -111,13 +91,10 @@ describe('Field', () => { }); it('should return all fields if filterFieldTypes was not specified', () => { - const aggParam = new FieldParamType( - { - name: 'field', - type: 'field', - }, - fieldParamTypeDependencies - ); + const aggParam = new FieldParamType({ + name: 'field', + type: 'field', + }); indexPattern.fields[1].aggregatable = true; diff --git a/src/plugins/data/public/search/aggs/param_types/field.ts b/src/plugins/data/public/search/aggs/param_types/field.ts index 63dbed9cec612..cb3617b02e882 100644 --- a/src/plugins/data/public/search/aggs/param_types/field.ts +++ b/src/plugins/data/public/search/aggs/param_types/field.ts @@ -19,12 +19,11 @@ import { i18n } from '@kbn/i18n'; import { IAggConfig } from '../agg_config'; -import { SavedObjectNotFound } from '../../../../../../plugins/kibana_utils/public'; +import { SavedObjectNotFound } from '../../../../../../plugins/kibana_utils/common'; import { BaseParamType } from './base'; import { propFilter } from '../utils'; import { isNestedField, KBN_FIELD_TYPES } from '../../../../common'; import { Field as IndexPatternField } from '../../../index_patterns'; -import { GetInternalStartServicesFn } from '../../../types'; const filterByType = propFilter('type'); @@ -32,20 +31,13 @@ export type FieldTypes = KBN_FIELD_TYPES | KBN_FIELD_TYPES[] | '*'; // TODO need to make a more explicit interface for this export type IFieldParamType = FieldParamType; -export interface FieldParamTypeDependencies { - getInternalStartServices: GetInternalStartServicesFn; -} - export class FieldParamType extends BaseParamType { required = true; scriptable = true; filterFieldTypes: FieldTypes; onlyAggregatable: boolean; - constructor( - config: Record, - { getInternalStartServices }: FieldParamTypeDependencies - ) { + constructor(config: Record) { super(config); this.filterFieldTypes = config.filterFieldTypes || '*'; @@ -91,10 +83,9 @@ export class FieldParamType extends BaseParamType { throw new SavedObjectNotFound('index-pattern-field', fieldName); } - // @ts-ignore const validField = this.getAvailableFields(aggConfig).find((f: any) => f.name === fieldName); if (!validField) { - getInternalStartServices().notifications.toasts.addDanger( + throw new Error( i18n.translate( 'data.search.aggs.paramTypes.field.invalidSavedFieldParameterErrorMessage', { diff --git a/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts b/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts index aa27bab8f4bd8..283e9107d3bb4 100644 --- a/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts +++ b/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts @@ -22,7 +22,7 @@ import { AnyExpressionFunctionDefinition, ExpressionFunctionDefinition, ExecutionContext, -} from '../../../../../../plugins/expressions/public'; +} from 'src/plugins/expressions/common'; /** * Takes a function spec and passes in default args, diff --git a/src/plugins/data/public/search/aggs/test_helpers/index.ts b/src/plugins/data/public/search/aggs/test_helpers/index.ts index 63f8ae0ce5f58..d47317d8b4725 100644 --- a/src/plugins/data/public/search/aggs/test_helpers/index.ts +++ b/src/plugins/data/public/search/aggs/test_helpers/index.ts @@ -19,4 +19,3 @@ export { functionWrapper } from './function_wrapper'; export { mockAggTypesRegistry } from './mock_agg_types_registry'; -export { mockDataServices } from './mock_data_services'; diff --git a/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts b/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts index 385d0cd6c6b39..4a0820c349b5f 100644 --- a/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts +++ b/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts @@ -17,7 +17,7 @@ * under the License. */ -import { coreMock, notificationServiceMock } from '../../../../../../../src/core/public/mocks'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; import { AggTypesRegistry, AggTypesRegistryStart } from '../agg_types_registry'; import { getAggTypes } from '../agg_types'; import { BucketAggType } from '../buckets/bucket_agg_type'; @@ -74,17 +74,11 @@ export function mockAggTypesRegistry | MetricAggTyp const coreSetup = coreMock.createSetup(); coreSetup.uiSettings.get = mockUiSettings; - const coreStart = coreMock.createStart(); - coreSetup.uiSettings.get = mockUiSettings; - const aggTypes = getAggTypes({ calculateBounds: jest.fn(), getInternalStartServices: () => (({ fieldFormats: fieldFormatsServiceMock.createStartContract(), - notifications: notificationServiceMock.createStartContract(), - uiSettings: coreStart.uiSettings, - injectedMetadata: coreStart.injectedMetadata, } as unknown) as InternalStartServices), uiSettings: coreSetup.uiSettings, }); diff --git a/src/plugins/data/public/search/aggs/test_helpers/mock_data_services.ts b/src/plugins/data/public/search/aggs/test_helpers/mock_data_services.ts deleted file mode 100644 index e807e084c683a..0000000000000 --- a/src/plugins/data/public/search/aggs/test_helpers/mock_data_services.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { coreMock } from '../../../../../../core/public/mocks'; -import { dataPluginMock } from '../../../mocks'; -import { - setFieldFormats, - setIndexPatterns, - setInjectedMetadata, - setNotifications, - setOverlays, - setQueryService, - setSearchService, - setUiSettings, -} from '../../../services'; - -/** - * Testing helper which calls all of the service setters used in the - * data plugin. Services are added using their provided mocks. - * - * @internal - */ -export function mockDataServices() { - const core = coreMock.createStart(); - const data = dataPluginMock.createStartContract(); - - setFieldFormats(data.fieldFormats); - setIndexPatterns(data.indexPatterns); - setInjectedMetadata(core.injectedMetadata); - setNotifications(core.notifications); - setOverlays(core.overlays); - setQueryService(data.query); - setSearchService(data.search); - setUiSettings(core.uiSettings); - - return { - core, - data, - }; -} diff --git a/src/plugins/data/public/search/expressions/create_filter.test.ts b/src/plugins/data/public/search/expressions/create_filter.test.ts index 23da060cba203..a7fd67983cb92 100644 --- a/src/plugins/data/public/search/expressions/create_filter.test.ts +++ b/src/plugins/data/public/search/expressions/create_filter.test.ts @@ -21,7 +21,7 @@ import { createFilter } from './create_filter'; import { AggConfigs, IAggConfig } from '../aggs'; import { TabbedTable } from '../tabify'; import { isRangeFilter, BytesFormat, FieldFormatsGetConfigFn } from '../../../common'; -import { mockDataServices, mockAggTypesRegistry } from '../aggs/test_helpers'; +import { mockAggTypesRegistry } from '../aggs/test_helpers'; describe('createFilter', () => { let table: TabbedTable; @@ -83,7 +83,6 @@ describe('createFilter', () => { }, ], }; - mockDataServices(); }); test('ignores event when cell value is not provided', async () => { diff --git a/src/plugins/data/public/search/expressions/esaggs.ts b/src/plugins/data/public/search/expressions/esaggs.ts index c2446e9cc5555..4ac6c823d2e3b 100644 --- a/src/plugins/data/public/search/expressions/esaggs.ts +++ b/src/plugins/data/public/search/expressions/esaggs.ts @@ -24,7 +24,7 @@ import { KibanaDatatable, ExpressionFunctionDefinition, KibanaDatatableColumn, -} from '../../../../../plugins/expressions/public'; +} from 'src/plugins/expressions/public'; import { calculateObjectHash } from '../../../../../plugins/kibana_utils/public'; import { PersistedState } from '../../../../../plugins/visualizations/public'; import { Adapters } from '../../../../../plugins/inspector/public'; @@ -201,7 +201,7 @@ const handleCourierRequest = async ({ aggs, agg, requestSearchSource, - inspectorAdapters, + inspectorAdapters.requests, abortSignal ); } diff --git a/src/plugins/data/public/search/expressions/utils/courier_inspector_stats.ts b/src/plugins/data/public/search/expressions/utils/courier_inspector_stats.ts index e54c20caacb26..96d0aaa16f6ba 100644 --- a/src/plugins/data/public/search/expressions/utils/courier_inspector_stats.ts +++ b/src/plugins/data/public/search/expressions/utils/courier_inspector_stats.ts @@ -26,12 +26,12 @@ import { i18n } from '@kbn/i18n'; import { SearchResponse } from 'elasticsearch'; -import { RequestInspectorStats } from './types'; +import { RequestStatistics } from 'src/plugins/inspector/common'; import { ISearchSource } from '../../search_source'; /** @public */ export function getRequestInspectorStats(searchSource: ISearchSource) { - const stats: RequestInspectorStats = {}; + const stats: RequestStatistics = {}; const index = searchSource.getField('index'); if (index) { @@ -65,7 +65,7 @@ export function getResponseInspectorStats( resp: SearchResponse ) { const lastRequest = searchSource.history && searchSource.history[searchSource.history.length - 1]; - const stats: RequestInspectorStats = {}; + const stats: RequestStatistics = {}; if (resp && resp.took) { stats.queryTime = { diff --git a/src/plugins/data/public/search/expressions/utils/types.ts b/src/plugins/data/public/search/expressions/utils/types.ts deleted file mode 100644 index b2311e664820e..0000000000000 --- a/src/plugins/data/public/search/expressions/utils/types.ts +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -interface InspectorStat { - label: string; - value: string; - description: string; -} - -/** @internal */ -export interface RequestInspectorStats { - indexPattern?: InspectorStat; - indexPatternId?: InspectorStat; - queryTime?: InspectorStat; - hitsTotal?: InspectorStat; - hits?: InspectorStat; - requestTime?: InspectorStat; -} diff --git a/src/plugins/data/public/search/tabify/get_columns.test.ts b/src/plugins/data/public/search/tabify/get_columns.test.ts index 35f0181f63302..7df4f5c947583 100644 --- a/src/plugins/data/public/search/tabify/get_columns.test.ts +++ b/src/plugins/data/public/search/tabify/get_columns.test.ts @@ -20,26 +20,27 @@ import { tabifyGetColumns } from './get_columns'; import { TabbedAggColumn } from './types'; import { AggConfigs } from '../aggs'; -import { mockAggTypesRegistry, mockDataServices } from '../aggs/test_helpers'; +import { mockAggTypesRegistry } from '../aggs/test_helpers'; describe('get columns', () => { - beforeEach(() => { - mockDataServices(); - }); - const typesRegistry = mockAggTypesRegistry(); const createAggConfigs = (aggs: any[] = []) => { - const field = { - name: '@timestamp', - }; + const fields = [ + { + name: '@timestamp', + }, + { + name: 'bytes', + }, + ]; const indexPattern = { id: '1234', title: 'logstash-*', fields: { - getByName: () => field, - filter: () => [field], + getByName: (name: string) => fields.find((f) => f.name === name), + filter: () => fields, }, } as any; diff --git a/src/plugins/data/public/search/tabify/response_writer.test.ts b/src/plugins/data/public/search/tabify/response_writer.test.ts index 94473d23ccc39..5a5ef8bd29524 100644 --- a/src/plugins/data/public/search/tabify/response_writer.test.ts +++ b/src/plugins/data/public/search/tabify/response_writer.test.ts @@ -19,14 +19,10 @@ import { TabbedAggResponseWriter } from './response_writer'; import { AggConfigs, BUCKET_TYPES } from '../aggs'; -import { mockDataServices, mockAggTypesRegistry } from '../aggs/test_helpers'; +import { mockAggTypesRegistry } from '../aggs/test_helpers'; import { TabbedResponseWriterOptions } from './types'; describe('TabbedAggResponseWriter class', () => { - beforeEach(() => { - mockDataServices(); - }); - let responseWriter: TabbedAggResponseWriter; const typesRegistry = mockAggTypesRegistry(); @@ -58,16 +54,21 @@ describe('TabbedAggResponseWriter class', () => { ]; const createResponseWritter = (aggs: any[] = [], opts?: Partial) => { - const field = { - name: 'geo.src', - }; + const fields = [ + { + name: 'geo.src', + }, + { + name: 'machine.os.raw', + }, + ]; const indexPattern = { id: '1234', title: 'logstash-*', fields: { - getByName: () => field, - filter: () => [field], + getByName: (name: string) => fields.find((f) => f.name === name), + filter: () => fields, }, } as any; diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts b/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts index 01a664837e704..114be67e490cf 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts @@ -18,12 +18,12 @@ */ import dateMath from '@elastic/datemath'; -import { Ipv4Address } from '../../../../../../kibana_utils/public'; import { FILTER_OPERATORS, Operator } from './filter_operators'; import { isFilterable, IIndexPattern, IFieldType, + Ipv4Address, Filter, FieldFilter, } from '../../../../../common'; diff --git a/src/plugins/data/public/ui/query_string_input/query_string_input.tsx b/src/plugins/data/public/ui/query_string_input/query_string_input.tsx index 120bbf3b68f7b..c746449f14c26 100644 --- a/src/plugins/data/public/ui/query_string_input/query_string_input.tsx +++ b/src/plugins/data/public/ui/query_string_input/query_string_input.tsx @@ -54,6 +54,7 @@ interface Props { bubbleSubmitEvent?: boolean; placeholder?: string; languageSwitcherPopoverAnchorPosition?: PopoverAnchorPosition; + onBlur?: () => void; onChange?: (query: Query) => void; onSubmit?: (query: Query) => void; dataTestSubj?: string; @@ -535,6 +536,7 @@ export class QueryStringInputUI extends Component { onKeyUp={this.onKeyUp} onChange={this.onInputChange} onClick={this.onClickInput} + onBlur={this.props.onBlur} fullWidth autoFocus={!this.props.disableAutoFocus} inputRef={(node) => { diff --git a/src/plugins/data/server/index.ts b/src/plugins/data/server/index.ts index 6a4eb38b552ff..0dd0115add8ad 100644 --- a/src/plugins/data/server/index.ts +++ b/src/plugins/data/server/index.ts @@ -155,6 +155,7 @@ import { dateHistogramInterval, InvalidEsCalendarIntervalError, InvalidEsIntervalFormatError, + Ipv4Address, isValidEsInterval, isValidInterval, parseEsInterval, @@ -184,6 +185,7 @@ export const search = { dateHistogramInterval, InvalidEsCalendarIntervalError, InvalidEsIntervalFormatError, + Ipv4Address, isValidEsInterval, isValidInterval, parseEsInterval, diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index f029609cbf7ec..0048816456e17 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -732,6 +732,7 @@ export const search: { dateHistogramInterval: typeof dateHistogramInterval; InvalidEsCalendarIntervalError: typeof InvalidEsCalendarIntervalError; InvalidEsIntervalFormatError: typeof InvalidEsIntervalFormatError; + Ipv4Address: typeof Ipv4Address; isValidEsInterval: typeof isValidEsInterval; isValidInterval: typeof isValidInterval; parseEsInterval: typeof parseEsInterval; @@ -820,12 +821,13 @@ export const UI_SETTINGS: { // src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "TruncateFormat" needs to be exported by the entry point index.d.ts // src/plugins/data/server/index.ts:129:27 - (ae-forgotten-export) The symbol "isFilterable" needs to be exported by the entry point index.d.ts // src/plugins/data/server/index.ts:129:27 - (ae-forgotten-export) The symbol "isNestedField" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:184:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:185:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:186:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:187:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:188:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:191:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:185:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:186:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:187:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:188:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:189:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:190:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:193:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts // (No @packageDocumentation comment for this package) diff --git a/src/plugins/inspector/common/adapters/index.ts b/src/plugins/inspector/common/adapters/index.ts index 8e1979ab33275..2fc465e7d0b2d 100644 --- a/src/plugins/inspector/common/adapters/index.ts +++ b/src/plugins/inspector/common/adapters/index.ts @@ -18,4 +18,4 @@ */ export { DataAdapter, FormattedData } from './data'; -export { RequestAdapter, RequestStatus } from './request'; +export { RequestAdapter, RequestStatistic, RequestStatistics, RequestStatus } from './request'; diff --git a/src/plugins/inspector/common/adapters/request/index.ts b/src/plugins/inspector/common/adapters/request/index.ts index 7359c56999a94..5c93757e86d05 100644 --- a/src/plugins/inspector/common/adapters/request/index.ts +++ b/src/plugins/inspector/common/adapters/request/index.ts @@ -17,6 +17,5 @@ * under the License. */ -export { RequestStatus } from './types'; - +export { RequestStatistic, RequestStatistics, RequestStatus } from './types'; export { RequestAdapter } from './request_adapter'; diff --git a/src/plugins/kibana_utils/public/index.ts b/src/plugins/kibana_utils/public/index.ts index 2911a9ae75689..e2d6ae647abb1 100644 --- a/src/plugins/kibana_utils/public/index.ts +++ b/src/plugins/kibana_utils/public/index.ts @@ -35,7 +35,6 @@ export { export * from './core'; export * from '../common/errors'; export * from './field_wildcard'; -export * from './parse'; export * from './render_complete'; export * from './resize_checker'; export * from '../common/state_containers'; diff --git a/src/plugins/kibana_utils/public/parse/index.ts b/src/plugins/kibana_utils/public/parse/index.ts deleted file mode 100644 index 997cf1b9ae4d1..0000000000000 --- a/src/plugins/kibana_utils/public/parse/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export * from './ipv4_address'; diff --git a/src/plugins/vis_default_editor/public/components/controls/components/from_to_list.tsx b/src/plugins/vis_default_editor/public/components/controls/components/from_to_list.tsx index 8fe5cdb47a53d..c0c46f6714c2d 100644 --- a/src/plugins/vis_default_editor/public/components/controls/components/from_to_list.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/components/from_to_list.tsx @@ -21,7 +21,7 @@ import React, { useCallback } from 'react'; import { EuiFieldText, EuiFlexItem, EuiIcon } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { Ipv4Address } from '../../../../../kibana_utils/public'; +import { search } from '../../../../../data/public'; import { InputList, InputListConfig, InputModel, InputObject, InputItem } from './input_list'; const EMPTY_STRING = ''; @@ -49,7 +49,7 @@ const defaultConfig = { from: { value: '0.0.0.0', model: '0.0.0.0', isInvalid: false }, to: { value: '255.255.255.255', model: '255.255.255.255', isInvalid: false }, }, - validateClass: Ipv4Address, + validateClass: search.aggs.Ipv4Address, getModelValue: (item: FromToObject = {}) => ({ from: { value: item.from || EMPTY_STRING, diff --git a/src/plugins/vis_default_editor/public/components/controls/filter.tsx b/src/plugins/vis_default_editor/public/components/controls/filter.tsx index 0228c79139f16..94fd2d9bc9151 100644 --- a/src/plugins/vis_default_editor/public/components/controls/filter.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/filter.tsx @@ -22,6 +22,7 @@ import { EuiForm, EuiButtonIcon, EuiFieldText, EuiFormRow, EuiSpacer } from '@el import { i18n } from '@kbn/i18n'; import { IAggConfig, Query, QueryStringInput } from '../../../../data/public'; +import { useKibana } from '../../../../kibana_react/public'; interface FilterRowProps { id: string; @@ -48,6 +49,7 @@ function FilterRow({ onChangeValue, onRemoveFilter, }: FilterRowProps) { + const { services } = useKibana(); const [showCustomLabel, setShowCustomLabel] = useState(false); const filterLabel = i18n.translate('visDefaultEditor.controls.filters.filterLabel', { defaultMessage: 'Filter {index}', @@ -56,6 +58,13 @@ function FilterRow({ }, }); + const onBlur = () => { + if (value.query.length > 0) { + // Store filter to the query log so that it is available in autocomplete. + services.data.query.addToQueryLog(services.appName, value); + } + }; + const FilterControl = (
onChangeValue(id, query, customLabel)} + onBlur={onBlur} disableAutoFocus={!autoFocus} dataTestSubj={dataTestSubj} bubbleSubmitEvent={true} diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.ts b/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.ts index 888c881f45ce4..483ca5d6d332e 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.ts +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.ts @@ -7,8 +7,8 @@ import dateMath from '@elastic/datemath'; import { EuiComboBoxOptionOption } from '@elastic/eui'; -import { IFieldType } from '../../../../../../../src/plugins/data/common'; -import { Ipv4Address } from '../../../../../../../src/plugins/kibana_utils/public'; +import { IFieldType, Ipv4Address } from '../../../../../../../src/plugins/data/common'; + import { EXCEPTION_OPERATORS, isOperator,