From 08c845deede03511558de2c50d404d47a439bf48 Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Tue, 21 Jan 2020 18:54:45 +0300 Subject: [PATCH 01/13] Expose NP FieldFormats service to server side --- src/legacy/core_plugins/kibana/index.js | 2 - .../kibana/server/field_formats/register.js | 54 ------------ .../mixin/field_formats_mixin.ts | 45 ---------- src/legacy/ui/ui_mixin.js | 2 - .../field_formats/field_formats.test.ts} | 10 +-- .../server/field_formats/field_formats.ts} | 9 +- .../field_formats/field_formats_service.ts | 87 +++++++++++++++++++ .../data/server}/field_formats/index.ts | 7 +- src/plugins/data/server/index.ts | 10 ++- src/plugins/data/server/plugin.ts | 22 ++++- .../csv/server/__tests__/execute_job.js | 8 +- x-pack/legacy/plugins/reporting/index.ts | 8 +- .../legacy/plugins/reporting/server/plugin.ts | 4 +- 13 files changed, 142 insertions(+), 126 deletions(-) delete mode 100644 src/legacy/core_plugins/kibana/server/field_formats/register.js delete mode 100644 src/legacy/ui/field_formats/mixin/field_formats_mixin.ts rename src/{legacy/ui/field_formats/mixin/field_formats_service.test.ts => plugins/data/server/field_formats/field_formats.test.ts} (83%) rename src/{legacy/ui/field_formats/mixin/field_formats_service.ts => plugins/data/server/field_formats/field_formats.ts} (91%) create mode 100644 src/plugins/data/server/field_formats/field_formats_service.ts rename src/{legacy/ui => plugins/data/server}/field_formats/index.ts (82%) diff --git a/src/legacy/core_plugins/kibana/index.js b/src/legacy/core_plugins/kibana/index.js index 55bd852050218..f60e100869d93 100644 --- a/src/legacy/core_plugins/kibana/index.js +++ b/src/legacy/core_plugins/kibana/index.js @@ -26,7 +26,6 @@ import { importApi } from './server/routes/api/import'; import { exportApi } from './server/routes/api/export'; import { homeApi } from './server/routes/api/home'; import { managementApi } from './server/routes/api/management'; -import { registerFieldFormats } from './server/field_formats/register'; import { registerTutorials } from './server/tutorials/register'; import * as systemApi from './server/lib/system_api'; import mappings from './mappings.json'; @@ -334,7 +333,6 @@ export default function(kibana) { exportApi(server); homeApi(server); managementApi(server); - registerFieldFormats(server); registerTutorials(server); registerCspCollector(usageCollection, server); server.expose('systemApi', systemApi); diff --git a/src/legacy/core_plugins/kibana/server/field_formats/register.js b/src/legacy/core_plugins/kibana/server/field_formats/register.js deleted file mode 100644 index 34dc06aab44ac..0000000000000 --- a/src/legacy/core_plugins/kibana/server/field_formats/register.js +++ /dev/null @@ -1,54 +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. - */ - -import { - UrlFormat, - StringFormat, - NumberFormat, - BytesFormat, - TruncateFormat, - RelativeDateFormat, - PercentFormat, - IpFormat, - DurationFormat, - DateNanosFormat, - DateFormat, - ColorFormat, - BoolFormat, - SourceFormat, - StaticLookupFormat, -} from '../../../../../plugins/data/server'; - -export function registerFieldFormats(server) { - server.registerFieldFormat(UrlFormat); - server.registerFieldFormat(BytesFormat); - server.registerFieldFormat(DateFormat); - server.registerFieldFormat(DateNanosFormat); - server.registerFieldFormat(RelativeDateFormat); - server.registerFieldFormat(DurationFormat); - server.registerFieldFormat(IpFormat); - server.registerFieldFormat(NumberFormat); - server.registerFieldFormat(PercentFormat); - server.registerFieldFormat(StringFormat); - server.registerFieldFormat(SourceFormat); - server.registerFieldFormat(ColorFormat); - server.registerFieldFormat(TruncateFormat); - server.registerFieldFormat(BoolFormat); - server.registerFieldFormat(StaticLookupFormat); -} diff --git a/src/legacy/ui/field_formats/mixin/field_formats_mixin.ts b/src/legacy/ui/field_formats/mixin/field_formats_mixin.ts deleted file mode 100644 index 370c312706242..0000000000000 --- a/src/legacy/ui/field_formats/mixin/field_formats_mixin.ts +++ /dev/null @@ -1,45 +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. - */ - -import { has } from 'lodash'; -import { Legacy } from 'kibana'; -import { FieldFormatsService } from './field_formats_service'; -import { IFieldFormatType } from '../../../../plugins/data/public'; - -export function fieldFormatsMixin(kbnServer: any, server: Legacy.Server) { - const fieldFormatClasses: IFieldFormatType[] = []; - - // for use outside of the request context, for special cases - server.decorate('server', 'fieldFormatServiceFactory', async function(uiSettings) { - const uiConfigs = await uiSettings.getAll(); - const registeredUiSettings = uiSettings.getRegistered(); - Object.keys(registeredUiSettings).forEach(key => { - if (has(uiConfigs, key) && registeredUiSettings[key].type === 'json') { - uiConfigs[key] = JSON.parse(uiConfigs[key]); - } - }); - const getConfig = (key: string) => uiConfigs[key]; - - return new FieldFormatsService(fieldFormatClasses, getConfig); - }); - - server.decorate('server', 'registerFieldFormat', customFieldFormat => { - fieldFormatClasses.push(customFieldFormat); - }); -} diff --git a/src/legacy/ui/ui_mixin.js b/src/legacy/ui/ui_mixin.js index 24d22efe4fa06..4261ce88e7726 100644 --- a/src/legacy/ui/ui_mixin.js +++ b/src/legacy/ui/ui_mixin.js @@ -17,7 +17,6 @@ * under the License. */ -import { fieldFormatsMixin } from './field_formats'; import { tutorialsMixin } from './tutorials_mixin'; import { uiAppsMixin } from './ui_apps'; import { uiBundlesMixin } from './ui_bundles'; @@ -28,7 +27,6 @@ export async function uiMixin(kbnServer) { await kbnServer.mixin(uiAppsMixin); await kbnServer.mixin(uiBundlesMixin); await kbnServer.mixin(uiSettingsMixin); - await kbnServer.mixin(fieldFormatsMixin); await kbnServer.mixin(tutorialsMixin); await kbnServer.mixin(uiRenderMixin); } diff --git a/src/legacy/ui/field_formats/mixin/field_formats_service.test.ts b/src/plugins/data/server/field_formats/field_formats.test.ts similarity index 83% rename from src/legacy/ui/field_formats/mixin/field_formats_service.test.ts rename to src/plugins/data/server/field_formats/field_formats.test.ts index 4ca181d3f69d4..54e6baa4b64d2 100644 --- a/src/legacy/ui/field_formats/mixin/field_formats_service.test.ts +++ b/src/plugins/data/server/field_formats/field_formats.test.ts @@ -17,7 +17,7 @@ * under the License. */ -import { FieldFormatsService } from './field_formats_service'; +import { FieldFormats } from './field_formats'; import { NumberFormat } from '../../../../plugins/data/public'; const getConfig = (key: string) => { @@ -33,22 +33,22 @@ const getConfig = (key: string) => { }; describe('FieldFormatsService', () => { - let fieldFormatsService: FieldFormatsService; + let fieldFormats: FieldFormats; beforeEach(() => { const fieldFormatClasses = [NumberFormat]; - fieldFormatsService = new FieldFormatsService(fieldFormatClasses, getConfig); + fieldFormats = new FieldFormats(fieldFormatClasses, getConfig); }); test('FieldFormats are accessible via getType method', () => { - const Type = fieldFormatsService.getType('number'); + const Type = fieldFormats.getType('number'); expect(Type.id).toBe('number'); }); test('getDefaultInstance returns default FieldFormat instance for fieldType', () => { - const instance = fieldFormatsService.getDefaultInstance('number'); + const instance = fieldFormats.getDefaultInstance('number'); expect(instance.type.id).toBe('number'); expect(instance.convert('0.33333')).toBe('0.333'); diff --git a/src/legacy/ui/field_formats/mixin/field_formats_service.ts b/src/plugins/data/server/field_formats/field_formats.ts similarity index 91% rename from src/legacy/ui/field_formats/mixin/field_formats_service.ts rename to src/plugins/data/server/field_formats/field_formats.ts index c5bc25333985b..617efe845a751 100644 --- a/src/legacy/ui/field_formats/mixin/field_formats_service.ts +++ b/src/plugins/data/server/field_formats/field_formats.ts @@ -25,13 +25,11 @@ interface FieldFormatConfig { params?: Record; } -export class FieldFormatsService { - getConfig: any; - _fieldFormats: Dictionary; +export class FieldFormats { + private readonly _fieldFormats: Dictionary; - constructor(fieldFormatClasses: IFieldFormatType[], getConfig: Function) { + constructor(fieldFormatClasses: IFieldFormatType[], private getConfig: Function) { this._fieldFormats = indexBy(fieldFormatClasses, 'id'); - this.getConfig = getConfig; } /** @@ -43,6 +41,7 @@ export class FieldFormatsService { */ getDefaultConfig(fieldType: string): FieldFormatConfig { const defaultMap = this.getConfig('format:defaultTypeMap'); + return defaultMap[fieldType] || defaultMap._default_; } diff --git a/src/plugins/data/server/field_formats/field_formats_service.ts b/src/plugins/data/server/field_formats/field_formats_service.ts new file mode 100644 index 0000000000000..5bd207c45c7b0 --- /dev/null +++ b/src/plugins/data/server/field_formats/field_formats_service.ts @@ -0,0 +1,87 @@ +/* + * 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 { has } from 'lodash'; +import { FieldFormats } from './field_formats'; +import { IFieldFormatType } from '../../common/field_formats'; +import { IUiSettingsClient } from '../../../../core/server'; + +import { + UrlFormat, + StringFormat, + NumberFormat, + BytesFormat, + TruncateFormat, + RelativeDateFormat, + PercentFormat, + IpFormat, + DurationFormat, + DateNanosFormat, + DateFormat, + ColorFormat, + BoolFormat, + SourceFormat, + StaticLookupFormat, +} from '../../common/field_formats'; + +export class FieldFormatsService { + private readonly fieldFormatClasses: IFieldFormatType[] = [ + UrlFormat, + StringFormat, + NumberFormat, + BytesFormat, + TruncateFormat, + RelativeDateFormat, + PercentFormat, + IpFormat, + DurationFormat, + DateNanosFormat, + DateFormat, + ColorFormat, + BoolFormat, + SourceFormat, + StaticLookupFormat, + ]; + + public setup() { + return { + registerFieldFormat: (customFieldFormat: IFieldFormatType) => + this.fieldFormatClasses.push(customFieldFormat), + }; + } + + public start() { + return { + fieldFormatServiceFactory: async (uiSettings: IUiSettingsClient) => { + const uiConfigs = await uiSettings.getAll(); + const registeredUiSettings = uiSettings.getRegistered(); + + Object.keys(registeredUiSettings).forEach(key => { + if (has(uiConfigs, key) && registeredUiSettings[key].type === 'json') { + uiConfigs[key] = JSON.parse(uiConfigs[key]); + } + }); + + return new FieldFormats(this.fieldFormatClasses, (key: string) => uiConfigs[key]); + }, + }; + } +} + +export type FieldFormatsServiceSetup = ReturnType; +export type FieldFormatsServiceStart = ReturnType; diff --git a/src/legacy/ui/field_formats/index.ts b/src/plugins/data/server/field_formats/index.ts similarity index 82% rename from src/legacy/ui/field_formats/index.ts rename to src/plugins/data/server/field_formats/index.ts index e5cc2cb33d087..1848a6b64abd2 100644 --- a/src/legacy/ui/field_formats/index.ts +++ b/src/plugins/data/server/field_formats/index.ts @@ -17,4 +17,9 @@ * under the License. */ -export { fieldFormatsMixin } from './mixin/field_formats_mixin'; +export { + FieldFormatsService, + FieldFormatsServiceSetup, + FieldFormatsServiceStart, +} from './field_formats_service'; +export { FieldFormats } from './field_formats'; diff --git a/src/plugins/data/server/index.ts b/src/plugins/data/server/index.ts index 3cd088744a439..18b3e467b614b 100644 --- a/src/plugins/data/server/index.ts +++ b/src/plugins/data/server/index.ts @@ -18,12 +18,14 @@ */ import { PluginInitializerContext } from '../../../core/server'; -import { DataServerPlugin, DataPluginSetup } from './plugin'; +import { DataServerPlugin, DataPluginSetup, DataPluginStart } from './plugin'; export function plugin(initializerContext: PluginInitializerContext) { return new DataServerPlugin(initializerContext); } +export { FieldFormatsService, FieldFormats } from './field_formats'; + /** * Types to be shared externally * @public @@ -93,4 +95,8 @@ export { getKbnTypeNames, } from '../common'; -export { DataServerPlugin as Plugin, DataPluginSetup as PluginSetup }; +export { + DataServerPlugin as Plugin, + DataPluginSetup as PluginSetup, + DataPluginStart as PluginStart, +}; diff --git a/src/plugins/data/server/plugin.ts b/src/plugins/data/server/plugin.ts index 591fdb4c4080d..35df522392412 100644 --- a/src/plugins/data/server/plugin.ts +++ b/src/plugins/data/server/plugin.ts @@ -25,20 +25,32 @@ import { ScriptsService } from './scripts'; import { KqlTelemetryService } from './kql_telemetry'; import { UsageCollectionSetup } from '../../usage_collection/server'; import { AutocompleteService } from './autocomplete'; +import { + FieldFormatsService, + FieldFormatsServiceSetup, + FieldFormatsServiceStart, +} from './field_formats'; export interface DataPluginSetup { search: ISearchSetup; + fieldFormats: FieldFormatsServiceSetup; +} + +export interface DataPluginStart { + fieldFormats: FieldFormatsServiceStart; } export interface DataPluginSetupDependencies { usageCollection?: UsageCollectionSetup; } -export class DataServerPlugin implements Plugin { + +export class DataServerPlugin implements Plugin { private readonly searchService: SearchService; private readonly scriptsService: ScriptsService; private readonly kqlTelemetryService: KqlTelemetryService; private readonly autocompleteService = new AutocompleteService(); private readonly indexPatterns = new IndexPatternsService(); + private readonly fieldFormats = new FieldFormatsService(); constructor(initializerContext: PluginInitializerContext) { this.searchService = new SearchService(initializerContext); @@ -53,11 +65,17 @@ export class DataServerPlugin implements Plugin { this.kqlTelemetryService.setup(core, { usageCollection }); return { + fieldFormats: this.fieldFormats.setup(), search: this.searchService.setup(core), }; } - public start(core: CoreStart) {} + public start(core: CoreStart) { + return { + fieldFormats: this.fieldFormats.start(), + }; + } + public stop() {} } diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js b/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js index 83be303191bad..88a74900cba1b 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js @@ -10,10 +10,10 @@ import sinon from 'sinon'; import nodeCrypto from '@elastic/node-crypto'; import { CancellationToken } from '../../../../common/cancellation_token'; -import { FieldFormatsService } from '../../../../../../../../src/legacy/ui/field_formats/mixin/field_formats_service'; + // Reporting uses an unconventional directory structure so the linter marks this as a violation // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { StringFormat } from '../../../../../../../../src/plugins/data/server'; +import { StringFormat, FieldFormats } from '../../../../../../../../src/plugins/data/server'; import { executeJobFactory } from '../execute_job'; @@ -84,8 +84,8 @@ describe('CSV Execute Job', function() { uiConfigMock['format:defaultTypeMap'] = { _default_: { id: 'string', params: {} }, }; - const getConfig = key => uiConfigMock[key]; - return new FieldFormatsService([StringFormat], getConfig); + + return new FieldFormats([StringFormat], uiConfigMock); }, plugins: { elasticsearch: { diff --git a/x-pack/legacy/plugins/reporting/index.ts b/x-pack/legacy/plugins/reporting/index.ts index 52e26b3132007..252f7de21e4d8 100644 --- a/x-pack/legacy/plugins/reporting/index.ts +++ b/x-pack/legacy/plugins/reporting/index.ts @@ -17,6 +17,8 @@ import { reportingPluginFactory, } from './server/plugin'; +import { PluginStart as DataPluginStart } from '../../../../src/plugins/data/server'; + const kbToBase64Length = (kb: number) => { return Math.floor((kb * 1024 * 8) / 6); }; @@ -70,6 +72,9 @@ export const reporting = (kibana: any) => { const pluginsSetup: ReportingSetupDeps = { usageCollection: server.newPlatform.setup.plugins.usageCollection, }; + + const data = server.newPlatform.setup.plugins.data as DataPluginStart; + const __LEGACY: LegacySetup = { config: server.config, info: server.info, @@ -80,9 +85,8 @@ export const reporting = (kibana: any) => { security: server.plugins.security, }, savedObjects: server.savedObjects, + fieldFormatServiceFactory: data.fieldFormats.fieldFormatServiceFactory, uiSettingsServiceFactory: server.uiSettingsServiceFactory, - // @ts-ignore Property 'fieldFormatServiceFactory' does not exist on type 'Server'. - fieldFormatServiceFactory: server.fieldFormatServiceFactory, log: server.log.bind(server), }; diff --git a/x-pack/legacy/plugins/reporting/server/plugin.ts b/x-pack/legacy/plugins/reporting/server/plugin.ts index 934a3487209c4..06d50c297ee4f 100644 --- a/x-pack/legacy/plugins/reporting/server/plugin.ts +++ b/x-pack/legacy/plugins/reporting/server/plugin.ts @@ -6,7 +6,6 @@ import { Legacy } from 'kibana'; import { CoreSetup, CoreStart, Plugin } from 'src/core/server'; -import { IUiSettingsClient } from 'src/core/server'; import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; import { XPackMainPlugin } from '../../xpack_main/server/xpack_main'; // @ts-ignore @@ -18,6 +17,7 @@ import { LevelLogger, checkLicenseFactory, getExportTypesRegistry, runValidation import { createBrowserDriverFactory } from './browsers'; import { registerReportingUsageCollector } from './usage'; import { logConfiguration } from '../log_configuration'; +import { PluginStart as DataPluginStart } from '../../../../../src/plugins/data/server'; // For now there is no exposed functionality to other plugins export type ReportingSetup = object; @@ -44,7 +44,7 @@ export interface LegacySetup { route: Legacy.Server['route']; savedObjects: Legacy.Server['savedObjects']; uiSettingsServiceFactory: Legacy.Server['uiSettingsServiceFactory']; - fieldFormatServiceFactory: (uiConfig: IUiSettingsClient) => unknown; + fieldFormatServiceFactory: DataPluginStart['fieldFormats']['fieldFormatServiceFactory']; } export type ReportingPlugin = Plugin< From 7752b6eb80b8745190e33e0b854c327b06ffedfc Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Wed, 22 Jan 2020 10:30:43 +0300 Subject: [PATCH 02/13] fix CI --- .eslintrc.js | 10 +++++----- .../csv/server/__tests__/execute_job.js | 6 +----- .../export_types/csv/server/execute_job.ts | 9 ++------- .../csv/server/lib/field_format_map.test.ts | 12 +++++++----- .../csv/server/lib/field_format_map.ts | 2 +- x-pack/legacy/plugins/reporting/index.ts | 14 ++++++++++++-- x-pack/legacy/plugins/reporting/types.d.ts | 11 +---------- 7 files changed, 29 insertions(+), 35 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 2c5804da053a6..06847d0799b3f 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -244,15 +244,15 @@ module.exports = { { target: [ '(src|x-pack)/plugins/**/*', - '!(src|x-pack)/plugins/*/server/**/*', + '!(src|x-pack)/plugins/**/server/**/*', 'src/legacy/core_plugins/**/*', - '!src/legacy/core_plugins/*/server/**/*', - '!src/legacy/core_plugins/*/index.{js,ts,tsx}', + '!src/legacy/core_plugins/**/server/**/*', + '!src/legacy/core_plugins/**/index.{js,ts,tsx}', 'x-pack/legacy/plugins/**/*', - '!x-pack/legacy/plugins/*/server/**/*', - '!x-pack/legacy/plugins/*/index.{js,ts,tsx}', + '!x-pack/legacy/plugins/**/server/**/*', + '!x-pack/legacy/plugins/**/index.{js,ts,tsx}', 'examples/**/*', '!examples/**/server/**/*', diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js b/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js index 88a74900cba1b..92fba6360b3df 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js @@ -10,9 +10,6 @@ import sinon from 'sinon'; import nodeCrypto from '@elastic/node-crypto'; import { CancellationToken } from '../../../../common/cancellation_token'; - -// Reporting uses an unconventional directory structure so the linter marks this as a violation -// eslint-disable-next-line @kbn/eslint/no-restricted-paths import { StringFormat, FieldFormats } from '../../../../../../../../src/plugins/data/server'; import { executeJobFactory } from '../execute_job'; @@ -84,8 +81,7 @@ describe('CSV Execute Job', function() { uiConfigMock['format:defaultTypeMap'] = { _default_: { id: 'string', params: {} }, }; - - return new FieldFormats([StringFormat], uiConfigMock); + return new FieldFormats([StringFormat], key => uiConfigMock[key]); }, plugins: { elasticsearch: { diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts index f35ffa0e45bfe..e417d916a52fb 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts @@ -5,12 +5,7 @@ */ import { i18n } from '@kbn/i18n'; -import { - ExecuteJobFactory, - ESQueueWorkerExecuteFn, - FieldFormats, - ServerFacade, -} from '../../../types'; +import { ExecuteJobFactory, ESQueueWorkerExecuteFn, ServerFacade } from '../../../types'; import { CSV_JOB_TYPE, PLUGIN_ID } from '../../../common/constants'; import { cryptoFactory, LevelLogger } from '../../../server/lib'; import { JobDocPayloadDiscoverCsv } from '../types'; @@ -89,7 +84,7 @@ export const executeJobFactory: ExecuteJobFactory { - const fieldFormats = (await server.fieldFormatServiceFactory(uiConfig)) as FieldFormats; + const fieldFormats = await server.fieldFormatServiceFactory(uiConfig); return fieldFormatMapFactory(indexPatternSavedObject, fieldFormats); })(), (async () => { diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts index b3384dd6ca51d..ff9521113bdf6 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts @@ -5,10 +5,12 @@ */ import expect from '@kbn/expect'; -import { FieldFormatsService } from '../../../../../../../../src/legacy/ui/field_formats/mixin/field_formats_service'; -// Reporting uses an unconventional directory structure so the linter marks this as a violation -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { BytesFormat, NumberFormat } from '../../../../../../../../src/plugins/data/server'; + +import { + BytesFormat, + NumberFormat, + FieldFormats, +} from '../../../../../../../../src/plugins/data/server'; import { fieldFormatMapFactory } from './field_format_map'; type ConfigValue = { number: { id: string; params: {} } } | string; @@ -34,7 +36,7 @@ describe('field format map', function() { const getConfig = (key: string) => configMock[key]; const testValue = '4000'; - const fieldFormats = new FieldFormatsService([BytesFormat, NumberFormat], getConfig); + const fieldFormats = new FieldFormats([BytesFormat, NumberFormat], getConfig); const formatMap = fieldFormatMapFactory(indexPatternSavedObject, fieldFormats); diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts index d013b5e75ee4d..d57a0ac4f40af 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts @@ -5,7 +5,7 @@ */ import _ from 'lodash'; -import { FieldFormats } from '../../../../types'; +import { FieldFormats } from '../../../../../../../../src/plugins/data/server'; interface IndexPatternSavedObject { attributes: { diff --git a/x-pack/legacy/plugins/reporting/index.ts b/x-pack/legacy/plugins/reporting/index.ts index 252f7de21e4d8..25b795dee1389 100644 --- a/x-pack/legacy/plugins/reporting/index.ts +++ b/x-pack/legacy/plugins/reporting/index.ts @@ -7,6 +7,7 @@ import { resolve } from 'path'; import { i18n } from '@kbn/i18n'; import { Legacy } from 'kibana'; +import { IUiSettingsClient } from 'kibana/server'; import { PLUGIN_ID, UI_SETTINGS_CUSTOM_PDF_LOGO } from './common/constants'; import { ReportingConfigOptions, ReportingPluginSpecOptions } from './types.d'; import { config as reportingConfig } from './config'; @@ -23,6 +24,10 @@ const kbToBase64Length = (kb: number) => { return Math.floor((kb * 1024 * 8) / 6); }; +interface ReportingDeps { + data: DataPluginStart; +} + export const reporting = (kibana: any) => { return new kibana.Plugin({ id: PLUGIN_ID, @@ -73,7 +78,12 @@ export const reporting = (kibana: any) => { usageCollection: server.newPlatform.setup.plugins.usageCollection, }; - const data = server.newPlatform.setup.plugins.data as DataPluginStart; + const fieldFormatServiceFactory = async (uiSettings: IUiSettingsClient) => { + const [, plugins] = await coreSetup.getStartServices(); + const { fieldFormats } = (plugins as ReportingDeps).data; + + return fieldFormats.fieldFormatServiceFactory(uiSettings); + }; const __LEGACY: LegacySetup = { config: server.config, @@ -85,7 +95,7 @@ export const reporting = (kibana: any) => { security: server.plugins.security, }, savedObjects: server.savedObjects, - fieldFormatServiceFactory: data.fieldFormats.fieldFormatServiceFactory, + fieldFormatServiceFactory, uiSettingsServiceFactory: server.uiSettingsServiceFactory, log: server.log.bind(server), }; diff --git a/x-pack/legacy/plugins/reporting/types.d.ts b/x-pack/legacy/plugins/reporting/types.d.ts index 47f384250dd53..e0c497b95828d 100644 --- a/x-pack/legacy/plugins/reporting/types.d.ts +++ b/x-pack/legacy/plugins/reporting/types.d.ts @@ -7,10 +7,7 @@ import { ResponseObject } from 'hapi'; import { EventEmitter } from 'events'; import { Legacy } from 'kibana'; -import { - ElasticsearchPlugin, - CallCluster, -} from '../../../../src/legacy/core_plugins/elasticsearch'; +import { CallCluster } from '../../../../src/legacy/core_plugins/elasticsearch'; import { CancellationToken } from './common/cancellation_token'; import { LevelLogger } from './server/lib/level_logger'; import { HeadlessChromiumDriverFactory } from './server/browsers/chromium/driver_factory'; @@ -355,9 +352,3 @@ export interface InterceptedRequest { frameId: string; resourceType: string; } - -export interface FieldFormats { - getConfig: number; - getInstance: (config: any) => any; - getDefaultInstance: (key: string) => any; -} From 0be461918b4c03c9865dddbeddfabbdb5f58f85a Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Wed, 22 Jan 2020 20:57:29 +0300 Subject: [PATCH 03/13] fix PR comments --- .../field_formats/base_converters.ts} | 42 ++++++++-- .../field_formats_registry.test.ts} | 43 +++++----- .../field_formats/field_formats_registry.ts} | 80 ++++++++----------- .../data/common/field_formats/index.ts | 2 + .../field_formats_service.ts | 58 ++++---------- .../index.ts | 1 - src/plugins/data/public/index.ts | 3 +- .../index_patterns/index_pattern.test.ts | 2 +- src/plugins/data/public/mocks.ts | 1 - src/plugins/data/public/plugin.ts | 2 +- src/plugins/data/public/types.ts | 2 +- .../field_formats/field_formats.test.ts | 56 ------------- .../server/field_formats/field_formats.ts | 78 ------------------ .../field_formats/field_formats_service.ts | 53 +++--------- .../data/server/field_formats/index.ts | 8 +- src/plugins/data/server/index.ts | 4 +- src/plugins/data/server/plugin.ts | 10 +-- src/test_utils/public/stub_field_formats.ts | 40 +--------- .../csv/server/__tests__/execute_job.js | 9 ++- .../csv/server/lib/field_format_map.test.ts | 6 +- .../csv/server/lib/field_format_map.ts | 11 ++- 21 files changed, 151 insertions(+), 360 deletions(-) rename src/plugins/data/{public/field_formats_provider/types.ts => common/field_formats/base_converters.ts} (55%) rename src/plugins/data/{public/field_formats_provider/field_formats.test.ts => common/field_formats/field_formats_registry.test.ts} (86%) rename src/plugins/data/{public/field_formats_provider/field_formats.ts => common/field_formats/field_formats_registry.ts} (82%) rename src/plugins/data/public/{field_formats_provider => field_formats}/field_formats_service.ts (62%) rename src/plugins/data/public/{field_formats_provider => field_formats}/index.ts (92%) delete mode 100644 src/plugins/data/server/field_formats/field_formats.test.ts delete mode 100644 src/plugins/data/server/field_formats/field_formats.ts diff --git a/src/plugins/data/public/field_formats_provider/types.ts b/src/plugins/data/common/field_formats/base_converters.ts similarity index 55% rename from src/plugins/data/public/field_formats_provider/types.ts rename to src/plugins/data/common/field_formats/base_converters.ts index fc33bf4d38f85..686c53a0f46c2 100644 --- a/src/plugins/data/public/field_formats_provider/types.ts +++ b/src/plugins/data/common/field_formats/base_converters.ts @@ -17,10 +17,40 @@ * under the License. */ -import { IFieldFormatId } from '../../common'; +import { IFieldFormatType } from './field_format'; -export interface FieldType { - id: IFieldFormatId; - params: Record; - es?: boolean; -} +import { + BoolFormat, + BytesFormat, + ColorFormat, + DateFormat, + DateNanosFormat, + DurationFormat, + IpFormat, + NumberFormat, + PercentFormat, + RelativeDateFormat, + SourceFormat, + StaticLookupFormat, + StringFormat, + TruncateFormat, + UrlFormat, +} from './converters'; + +export const baseConverters: IFieldFormatType[] = [ + BoolFormat, + BytesFormat, + ColorFormat, + DateFormat, + DateNanosFormat, + DurationFormat, + IpFormat, + NumberFormat, + PercentFormat, + RelativeDateFormat, + SourceFormat, + StaticLookupFormat, + StringFormat, + TruncateFormat, + UrlFormat, +]; diff --git a/src/plugins/data/public/field_formats_provider/field_formats.test.ts b/src/plugins/data/common/field_formats/field_formats_registry.test.ts similarity index 86% rename from src/plugins/data/public/field_formats_provider/field_formats.test.ts rename to src/plugins/data/common/field_formats/field_formats_registry.test.ts index 8ad6cff77abc0..c41c90a4295ed 100644 --- a/src/plugins/data/public/field_formats_provider/field_formats.test.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.test.ts @@ -16,32 +16,36 @@ * specific language governing permissions and limitations * under the License. */ -import { CoreSetup, IUiSettingsClient } from 'kibana/public'; - -import { FieldFormatRegisty } from './field_formats'; -import { - BoolFormat, - IFieldFormatType, - PercentFormat, - StringFormat, -} from '../../common/field_formats'; -import { coreMock } from '../../../../core/public/mocks'; +import { FieldFormatRegisty } from './field_formats_registry'; +import { BoolFormat, PercentFormat, StringFormat } from './converters'; +import { IFieldFormatType } from './field_format'; import { KBN_FIELD_TYPES } from '../../common'; const getValueOfPrivateField = (instance: any, field: string) => instance[field]; -const getUiSettingsMock = (data: any): IUiSettingsClient['get'] => () => data; describe('FieldFormatRegisty', () => { - let mockCoreSetup: CoreSetup; let fieldFormatRegisty: FieldFormatRegisty; + let defaultMap = {}; + const getConfig = (key: string) => defaultMap; beforeEach(() => { - mockCoreSetup = coreMock.createSetup(); fieldFormatRegisty = new FieldFormatRegisty(); + fieldFormatRegisty.init( + getConfig, + { + parsedUrl: { + origin: '', + pathname: '', + basePath: '', + }, + }, + [] + ); }); test('should allows to create an instance of "FieldFormatRegisty"', () => { expect(fieldFormatRegisty).toBeDefined(); + expect(getValueOfPrivateField(fieldFormatRegisty, 'fieldFormats')).toBeDefined(); expect(getValueOfPrivateField(fieldFormatRegisty, 'defaultMap')).toEqual({}); }); @@ -52,21 +56,12 @@ describe('FieldFormatRegisty', () => { expect(typeof fieldFormatRegisty.init).toBe('function'); }); - test('should set basePath value from "init" method', () => { - fieldFormatRegisty.init(mockCoreSetup); - - expect(getValueOfPrivateField(fieldFormatRegisty, 'basePath')).toBe( - mockCoreSetup.http.basePath.get() - ); - }); - test('should populate the "defaultMap" object', () => { - const defaultMap = { + defaultMap = { number: { id: 'number', params: {} }, }; - mockCoreSetup.uiSettings.get = getUiSettingsMock(defaultMap); - fieldFormatRegisty.init(mockCoreSetup); + fieldFormatRegisty.init(getConfig, {}, []); expect(getValueOfPrivateField(fieldFormatRegisty, 'defaultMap')).toEqual(defaultMap); }); }); diff --git a/src/plugins/data/public/field_formats_provider/field_formats.ts b/src/plugins/data/common/field_formats/field_formats_registry.ts similarity index 82% rename from src/plugins/data/public/field_formats_provider/field_formats.ts rename to src/plugins/data/common/field_formats/field_formats_registry.ts index d3d57d42028cd..e6eebd65ea514 100644 --- a/src/plugins/data/public/field_formats_provider/field_formats.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.ts @@ -19,7 +19,7 @@ // eslint-disable-next-line max-classes-per-file import { forOwn, isFunction, memoize } from 'lodash'; -import { IUiSettingsClient, CoreSetup } from 'kibana/public'; + import { ES_FIELD_TYPES, KBN_FIELD_TYPES, @@ -29,32 +29,32 @@ import { FieldFormat, IFieldFormatMetaParams, } from '../../common'; -import { FieldType } from './types'; - -export class FieldFormatRegisty { - private fieldFormats: Map; - private uiSettings!: IUiSettingsClient; - private defaultMap: Record; - private basePath?: string; - - constructor() { - this.fieldFormats = new Map(); - this.defaultMap = {}; - } - - getConfig = (key: string, override?: any) => this.uiSettings.get(key, override); - init({ uiSettings, http }: CoreSetup) { - this.uiSettings = uiSettings; - this.basePath = http.basePath.get(); +import { baseConverters } from './base_converters'; - this.parseDefaultTypeMap(this.uiSettings.get('format:defaultTypeMap')); +export interface IFieldFormatConfig { + id: IFieldFormatId; + params: Record; + es?: boolean; +} - this.uiSettings.getUpdate$().subscribe(({ key, newValue }) => { - if (key === 'format:defaultTypeMap') { - this.parseDefaultTypeMap(newValue); - } - }); +export class FieldFormatRegisty { + protected fieldFormats: Map = new Map(); + protected defaultMap: Record = {}; + protected metaParamsOptions: Record = {}; + protected getConfig?: Function; + + init( + getConfig: Function, + metaParamsOptions: Record = {}, + defaultFieldConverters: IFieldFormatType[] = baseConverters + ) { + const defaultTypeMap = getConfig('format:defaultTypeMap'); + + this.register(defaultFieldConverters); + this.parseDefaultTypeMap(defaultTypeMap); + this.getConfig = getConfig; + this.metaParamsOptions = metaParamsOptions; } /** @@ -65,7 +65,10 @@ export class FieldFormatRegisty { * @param {ES_FIELD_TYPES[]} esTypes - Array of ES data types * @return {FieldType} */ - getDefaultConfig = (fieldType: KBN_FIELD_TYPES, esTypes?: ES_FIELD_TYPES[]): FieldType => { + getDefaultConfig = ( + fieldType: KBN_FIELD_TYPES, + esTypes?: ES_FIELD_TYPES[] + ): IFieldFormatConfig => { const type = this.getDefaultTypeName(fieldType, esTypes); return ( @@ -151,13 +154,13 @@ export class FieldFormatRegisty { */ getInstance = memoize( (formatId: IFieldFormatId, params: Record = {}): FieldFormat => { - const DerivedFieldFormat = this.getType(formatId); + const ConcreteFieldFormat = this.getType(formatId); - if (!DerivedFieldFormat) { + if (!ConcreteFieldFormat) { throw new Error(`Field Format '${formatId}' not found!`); } - return new DerivedFieldFormat(params, this.getConfig); + return new ConcreteFieldFormat(params, this.getConfig); } ); @@ -171,13 +174,7 @@ export class FieldFormatRegisty { getDefaultInstancePlain(fieldType: KBN_FIELD_TYPES, esTypes?: ES_FIELD_TYPES[]): FieldFormat { const conf = this.getDefaultConfig(fieldType, esTypes); - const DerivedFieldFormat = this.getType(conf.id); - - if (!DerivedFieldFormat) { - throw new Error(`Field Format '${conf.id}' not found!`); - } - - return new DerivedFieldFormat(conf.params, this.getConfig); + return this.getInstance(conf.id, conf.params); } /** * Returns a cache key built by the given variables for caching in memoized @@ -233,11 +230,9 @@ export class FieldFormatRegisty { }); } - register = (fieldFormats: IFieldFormatType[]) => { + register(fieldFormats: IFieldFormatType[]) { fieldFormats.forEach(fieldFormat => this.fieldFormats.set(fieldFormat.id, fieldFormat)); - - return this; - }; + } /** * FieldFormat decorator - provide a one way to add meta-params for all field formatters @@ -268,16 +263,11 @@ export class FieldFormatRegisty { /** * Build Meta Params * - * @static * @param {Record} custom params * @return {Record} */ private buildMetaParams = (customParams: T): T => ({ - parsedUrl: { - origin: window.location.origin, - pathname: window.location.pathname, - basePath: this.basePath, - }, + ...this.metaParamsOptions, ...customParams, }); } diff --git a/src/plugins/data/common/field_formats/index.ts b/src/plugins/data/common/field_formats/index.ts index b1e8744e26745..4b55eac7064ae 100644 --- a/src/plugins/data/common/field_formats/index.ts +++ b/src/plugins/data/common/field_formats/index.ts @@ -24,6 +24,8 @@ export { IFieldFormatId, IFieldFormatMetaParams, } from './field_format'; +export { FieldFormatRegisty, IFieldFormatConfig } from './field_formats_registry'; export { getHighlightRequest, asPrettyString, getHighlightHtml } from './utils'; +export { baseConverters } from './base_converters'; export * from './converters'; export * from './constants'; diff --git a/src/plugins/data/public/field_formats_provider/field_formats_service.ts b/src/plugins/data/public/field_formats/field_formats_service.ts similarity index 62% rename from src/plugins/data/public/field_formats_provider/field_formats_service.ts rename to src/plugins/data/public/field_formats/field_formats_service.ts index 42abeecc6fda0..26846efd66885 100644 --- a/src/plugins/data/public/field_formats_provider/field_formats_service.ts +++ b/src/plugins/data/public/field_formats/field_formats_service.ts @@ -18,49 +18,25 @@ */ import { CoreSetup } from 'src/core/public'; -import { FieldFormatRegisty } from './field_formats'; - -import { - BoolFormat, - BytesFormat, - ColorFormat, - DateFormat, - DateNanosFormat, - DurationFormat, - IpFormat, - NumberFormat, - PercentFormat, - RelativeDateFormat, - SourceFormat, - StaticLookupFormat, - StringFormat, - TruncateFormat, - UrlFormat, -} from '../../common/'; +import { FieldFormatRegisty } from '../../common/field_formats'; export class FieldFormatsService { private readonly fieldFormats: FieldFormatRegisty = new FieldFormatRegisty(); public setup(core: CoreSetup) { - this.fieldFormats.init(core); - - this.fieldFormats.register([ - BoolFormat, - BytesFormat, - ColorFormat, - DateFormat, - DateNanosFormat, - DurationFormat, - IpFormat, - NumberFormat, - PercentFormat, - RelativeDateFormat, - SourceFormat, - StaticLookupFormat, - StringFormat, - TruncateFormat, - UrlFormat, - ]); + core.uiSettings.getUpdate$().subscribe(({ key, newValue }) => { + if (key === 'format:defaultTypeMap') { + this.fieldFormats.parseDefaultTypeMap(newValue); + } + }); + + this.fieldFormats.init(core.uiSettings.get, { + parsedUrl: { + origin: window.location.origin, + pathname: window.location.pathname, + basePath: core.http.basePath.get(), + }, + }); return this.fieldFormats as FieldFormatsSetup; } @@ -68,12 +44,10 @@ export class FieldFormatsService { public start() { return this.fieldFormats as FieldFormatsStart; } - - public stop() { - // nothing to do here yet - } } /** @public */ export type FieldFormatsSetup = Omit; + +/** @public */ export type FieldFormatsStart = Omit; diff --git a/src/plugins/data/public/field_formats_provider/index.ts b/src/plugins/data/public/field_formats/index.ts similarity index 92% rename from src/plugins/data/public/field_formats_provider/index.ts rename to src/plugins/data/public/field_formats/index.ts index 442d877c5316a..4550a5781535f 100644 --- a/src/plugins/data/public/field_formats_provider/index.ts +++ b/src/plugins/data/public/field_formats/index.ts @@ -17,5 +17,4 @@ * under the License. */ -export { FieldFormatRegisty } from './field_formats'; // TODO: Try to remove export { FieldFormatsService, FieldFormatsSetup, FieldFormatsStart } from './field_formats_service'; diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index 19ba246ce02dd..5d33b131430c0 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -37,6 +37,7 @@ export { IFieldFormat, IFieldFormatId, IFieldFormatType, + FieldFormatRegisty, // index patterns IIndexPattern, IFieldType, @@ -51,7 +52,7 @@ export { TimeRange, } from '../common'; -export * from './field_formats_provider'; +export * from './field_formats'; export * from './index_patterns'; export * from './search'; export * from './query'; diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts index 1f83e4bd5b80c..10963a54a9abb 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts @@ -31,7 +31,7 @@ import { setNotifications, setFieldFormats } from '../../services'; // Temporary disable eslint, will be removed after moving to new platform folder // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { notificationServiceMock } from '../../../../../core/public/notifications/notifications_service.mock'; -import { FieldFormatRegisty } from '../../field_formats_provider'; +import { FieldFormatRegisty } from '../../../common/field_formats'; jest.mock('../../../../kibana_utils/public', () => { const originalModule = jest.requireActual('../../../../kibana_utils/public'); diff --git a/src/plugins/data/public/mocks.ts b/src/plugins/data/public/mocks.ts index f44d40f533eed..cf54d77d19964 100644 --- a/src/plugins/data/public/mocks.ts +++ b/src/plugins/data/public/mocks.ts @@ -37,7 +37,6 @@ const autocompleteMock: any = { const fieldFormatsMock: PublicMethodsOf = { getByFieldType: jest.fn(), - getConfig: jest.fn(), getDefaultConfig: jest.fn(), getDefaultInstance: jest.fn() as any, getDefaultInstanceCacheResolver: jest.fn(), diff --git a/src/plugins/data/public/plugin.ts b/src/plugins/data/public/plugin.ts index ce8ca0317bd7d..a54da59159875 100644 --- a/src/plugins/data/public/plugin.ts +++ b/src/plugins/data/public/plugin.ts @@ -33,7 +33,7 @@ import { } from './types'; import { AutocompleteService } from './autocomplete'; import { SearchService } from './search/search_service'; -import { FieldFormatsService } from './field_formats_provider'; +import { FieldFormatsService } from './field_formats'; import { QueryService } from './query'; import { createIndexPatternSelect } from './ui/index_pattern_select'; import { IndexPatterns } from './index_patterns'; diff --git a/src/plugins/data/public/types.ts b/src/plugins/data/public/types.ts index d2af256302248..6b6ff5e62e63f 100644 --- a/src/plugins/data/public/types.ts +++ b/src/plugins/data/public/types.ts @@ -21,7 +21,7 @@ import { CoreStart } from 'src/core/public'; import { IStorageWrapper } from 'src/plugins/kibana_utils/public'; import { IUiActionsSetup, IUiActionsStart } from 'src/plugins/ui_actions/public'; import { AutocompleteSetup, AutocompleteStart } from './autocomplete/types'; -import { FieldFormatsSetup, FieldFormatsStart } from './field_formats_provider'; +import { FieldFormatsSetup, FieldFormatsStart } from './field_formats'; import { ISearchSetup, ISearchStart } from './search'; import { QuerySetup, QueryStart } from './query'; import { IndexPatternSelectProps } from './ui/index_pattern_select'; diff --git a/src/plugins/data/server/field_formats/field_formats.test.ts b/src/plugins/data/server/field_formats/field_formats.test.ts deleted file mode 100644 index 54e6baa4b64d2..0000000000000 --- a/src/plugins/data/server/field_formats/field_formats.test.ts +++ /dev/null @@ -1,56 +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. - */ - -import { FieldFormats } from './field_formats'; -import { NumberFormat } from '../../../../plugins/data/public'; - -const getConfig = (key: string) => { - switch (key) { - case 'format:defaultTypeMap': - return { - number: { id: 'number', params: {} }, - _default_: { id: 'string', params: {} }, - }; - case 'format:number:defaultPattern': - return '0,0.[000]'; - } -}; - -describe('FieldFormatsService', () => { - let fieldFormats: FieldFormats; - - beforeEach(() => { - const fieldFormatClasses = [NumberFormat]; - - fieldFormats = new FieldFormats(fieldFormatClasses, getConfig); - }); - - test('FieldFormats are accessible via getType method', () => { - const Type = fieldFormats.getType('number'); - - expect(Type.id).toBe('number'); - }); - - test('getDefaultInstance returns default FieldFormat instance for fieldType', () => { - const instance = fieldFormats.getDefaultInstance('number'); - - expect(instance.type.id).toBe('number'); - expect(instance.convert('0.33333')).toBe('0.333'); - }); -}); diff --git a/src/plugins/data/server/field_formats/field_formats.ts b/src/plugins/data/server/field_formats/field_formats.ts deleted file mode 100644 index 617efe845a751..0000000000000 --- a/src/plugins/data/server/field_formats/field_formats.ts +++ /dev/null @@ -1,78 +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. - */ - -import { indexBy, Dictionary } from 'lodash'; -import { FieldFormat, IFieldFormatType } from '../../../../plugins/data/common'; - -interface FieldFormatConfig { - id: string; - params?: Record; -} - -export class FieldFormats { - private readonly _fieldFormats: Dictionary; - - constructor(fieldFormatClasses: IFieldFormatType[], private getConfig: Function) { - this._fieldFormats = indexBy(fieldFormatClasses, 'id'); - } - - /** - * Get the id of the default type for this field type - * using the format:defaultTypeMap config map - * - * @param {String} fieldType - the field type - * @return {FieldFormatConfig} - */ - getDefaultConfig(fieldType: string): FieldFormatConfig { - const defaultMap = this.getConfig('format:defaultTypeMap'); - - return defaultMap[fieldType] || defaultMap._default_; - } - - /** - * Get the default fieldFormat instance for a field type. - * - * @param {String} fieldType - * @return {FieldFormat} - */ - getDefaultInstance(fieldType: string): FieldFormat { - return this.getInstance(this.getDefaultConfig(fieldType)); - } - - /** - * Get the fieldFormat instance for a field format configuration. - * - * @param {FieldFormatConfig} field format config - * @return {FieldFormat} - */ - getInstance(conf: FieldFormatConfig): FieldFormat { - // @ts-ignore - return new this._fieldFormats[conf.id](conf.params, this.getConfig); - } - - /** - * Get a FieldFormat type (class) by it's id. - * - * @param {String} fieldFormatId - the FieldFormat id - * @return {FieldFormat} - */ - getType(fieldFormatId: string): any { - return this._fieldFormats[fieldFormatId]; - } -} diff --git a/src/plugins/data/server/field_formats/field_formats_service.ts b/src/plugins/data/server/field_formats/field_formats_service.ts index 5bd207c45c7b0..076fca7fbf778 100644 --- a/src/plugins/data/server/field_formats/field_formats_service.ts +++ b/src/plugins/data/server/field_formats/field_formats_service.ts @@ -17,50 +17,15 @@ * under the License. */ import { has } from 'lodash'; -import { FieldFormats } from './field_formats'; -import { IFieldFormatType } from '../../common/field_formats'; +import { FieldFormatRegisty, IFieldFormatType, baseConverters } from '../../common/field_formats'; import { IUiSettingsClient } from '../../../../core/server'; -import { - UrlFormat, - StringFormat, - NumberFormat, - BytesFormat, - TruncateFormat, - RelativeDateFormat, - PercentFormat, - IpFormat, - DurationFormat, - DateNanosFormat, - DateFormat, - ColorFormat, - BoolFormat, - SourceFormat, - StaticLookupFormat, -} from '../../common/field_formats'; - export class FieldFormatsService { - private readonly fieldFormatClasses: IFieldFormatType[] = [ - UrlFormat, - StringFormat, - NumberFormat, - BytesFormat, - TruncateFormat, - RelativeDateFormat, - PercentFormat, - IpFormat, - DurationFormat, - DateNanosFormat, - DateFormat, - ColorFormat, - BoolFormat, - SourceFormat, - StaticLookupFormat, - ]; + private readonly fieldFormatClasses: IFieldFormatType[] = baseConverters; public setup() { return { - registerFieldFormat: (customFieldFormat: IFieldFormatType) => + register: (customFieldFormat: IFieldFormatType) => this.fieldFormatClasses.push(customFieldFormat), }; } @@ -68,6 +33,7 @@ export class FieldFormatsService { public start() { return { fieldFormatServiceFactory: async (uiSettings: IUiSettingsClient) => { + const fieldFormats = new FieldFormatRegisty(); const uiConfigs = await uiSettings.getAll(); const registeredUiSettings = uiSettings.getRegistered(); @@ -77,11 +43,16 @@ export class FieldFormatsService { } }); - return new FieldFormats(this.fieldFormatClasses, (key: string) => uiConfigs[key]); + fieldFormats.init((key: string) => uiConfigs[key], {}, this.fieldFormatClasses); + + return fieldFormats; }, }; } } -export type FieldFormatsServiceSetup = ReturnType; -export type FieldFormatsServiceStart = ReturnType; +/** @public */ +export type FieldFormatsSetup = ReturnType; + +/** @public */ +export type FieldFormatsStart = ReturnType; diff --git a/src/plugins/data/server/field_formats/index.ts b/src/plugins/data/server/field_formats/index.ts index 1848a6b64abd2..168e112d86b75 100644 --- a/src/plugins/data/server/field_formats/index.ts +++ b/src/plugins/data/server/field_formats/index.ts @@ -17,9 +17,5 @@ * under the License. */ -export { - FieldFormatsService, - FieldFormatsServiceSetup, - FieldFormatsServiceStart, -} from './field_formats_service'; -export { FieldFormats } from './field_formats'; +export { FieldFormatsService, FieldFormatsSetup, FieldFormatsStart } from './field_formats_service'; +export { FieldFormatRegisty } from '../../common/field_formats'; diff --git a/src/plugins/data/server/index.ts b/src/plugins/data/server/index.ts index 18b3e467b614b..e14ba90e7357d 100644 --- a/src/plugins/data/server/index.ts +++ b/src/plugins/data/server/index.ts @@ -24,8 +24,6 @@ export function plugin(initializerContext: PluginInitializerContext) { return new DataServerPlugin(initializerContext); } -export { FieldFormatsService, FieldFormats } from './field_formats'; - /** * Types to be shared externally * @public @@ -37,6 +35,8 @@ export { IFieldFormat, IFieldFormatId, IFieldFormatType, + IFieldFormatConfig, + FieldFormatRegisty, // index patterns IIndexPattern, IFieldType, diff --git a/src/plugins/data/server/plugin.ts b/src/plugins/data/server/plugin.ts index 35df522392412..fcd3b62b2ec67 100644 --- a/src/plugins/data/server/plugin.ts +++ b/src/plugins/data/server/plugin.ts @@ -25,19 +25,15 @@ import { ScriptsService } from './scripts'; import { KqlTelemetryService } from './kql_telemetry'; import { UsageCollectionSetup } from '../../usage_collection/server'; import { AutocompleteService } from './autocomplete'; -import { - FieldFormatsService, - FieldFormatsServiceSetup, - FieldFormatsServiceStart, -} from './field_formats'; +import { FieldFormatsService, FieldFormatsSetup, FieldFormatsStart } from './field_formats'; export interface DataPluginSetup { search: ISearchSetup; - fieldFormats: FieldFormatsServiceSetup; + fieldFormats: FieldFormatsSetup; } export interface DataPluginStart { - fieldFormats: FieldFormatsServiceStart; + fieldFormats: FieldFormatsStart; } export interface DataPluginSetupDependencies { diff --git a/src/test_utils/public/stub_field_formats.ts b/src/test_utils/public/stub_field_formats.ts index ea46710c0dc84..5244569b1de59 100644 --- a/src/test_utils/public/stub_field_formats.ts +++ b/src/test_utils/public/stub_field_formats.ts @@ -17,48 +17,12 @@ * under the License. */ import { CoreSetup } from 'kibana/public'; - -import { - FieldFormatRegisty, - BoolFormat, - BytesFormat, - ColorFormat, - DateFormat, - DateNanosFormat, - DurationFormat, - IpFormat, - NumberFormat, - PercentFormat, - RelativeDateFormat, - SourceFormat, - StaticLookupFormat, - StringFormat, - TruncateFormat, - UrlFormat, -} from '../../plugins/data/public/'; +import { FieldFormatRegisty } from '../../plugins/data/public'; export const getFieldFormatsRegistry = (core: CoreSetup) => { const fieldFormats = new FieldFormatRegisty(); - fieldFormats.register([ - BoolFormat, - BytesFormat, - ColorFormat, - DateFormat, - DateNanosFormat, - DurationFormat, - IpFormat, - NumberFormat, - PercentFormat, - RelativeDateFormat, - SourceFormat, - StaticLookupFormat, - StringFormat, - TruncateFormat, - UrlFormat, - ]); - - fieldFormats.init(core); + fieldFormats.init(core.uiSettings.get, {}); return fieldFormats; }; diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js b/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js index 92fba6360b3df..c28276db37b2c 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js @@ -10,7 +10,7 @@ import sinon from 'sinon'; import nodeCrypto from '@elastic/node-crypto'; import { CancellationToken } from '../../../../common/cancellation_token'; -import { StringFormat, FieldFormats } from '../../../../../../../../src/plugins/data/server'; +import { StringFormat, FieldFormatRegisty } from '../../../../../../../../src/plugins/data/server'; import { executeJobFactory } from '../execute_job'; @@ -81,7 +81,12 @@ describe('CSV Execute Job', function() { uiConfigMock['format:defaultTypeMap'] = { _default_: { id: 'string', params: {} }, }; - return new FieldFormats([StringFormat], key => uiConfigMock[key]); + + const fieldFormatsService = new FieldFormatRegisty(); + + fieldFormatsService.init(key => uiConfigMock[key], {}, [StringFormat]); + + return fieldFormatsService; }, plugins: { elasticsearch: { diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts index ff9521113bdf6..016870ea11814 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { BytesFormat, NumberFormat, - FieldFormats, + FieldFormatRegisty, } from '../../../../../../../../src/plugins/data/server'; import { fieldFormatMapFactory } from './field_format_map'; @@ -36,8 +36,8 @@ describe('field format map', function() { const getConfig = (key: string) => configMock[key]; const testValue = '4000'; - const fieldFormats = new FieldFormats([BytesFormat, NumberFormat], getConfig); - + const fieldFormats = new FieldFormatRegisty(); + fieldFormats.init(getConfig, {}, [BytesFormat, NumberFormat]); const formatMap = fieldFormatMapFactory(indexPatternSavedObject, fieldFormats); it('should build field format map with entry per index pattern field', function() { diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts index d57a0ac4f40af..635a6e29a4e91 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts @@ -5,7 +5,10 @@ */ import _ from 'lodash'; -import { FieldFormats } from '../../../../../../../../src/plugins/data/server'; +import { + FieldFormatRegisty, + IFieldFormatConfig, +} from '../../../../../../../../src/plugins/data/server'; interface IndexPatternSavedObject { attributes: { @@ -25,7 +28,7 @@ interface IndexPatternSavedObject { */ export function fieldFormatMapFactory( indexPatternSavedObject: IndexPatternSavedObject, - fieldFormats: FieldFormats + fieldFormats: FieldFormatRegisty ) { const formatsMap = new Map(); @@ -33,10 +36,10 @@ export function fieldFormatMapFactory( if (_.has(indexPatternSavedObject, 'attributes.fieldFormatMap')) { const fieldFormatMap = JSON.parse(indexPatternSavedObject.attributes.fieldFormatMap); Object.keys(fieldFormatMap).forEach(fieldName => { - const formatConfig = fieldFormatMap[fieldName]; + const formatConfig: IFieldFormatConfig = fieldFormatMap[fieldName]; if (!_.isEmpty(formatConfig)) { - formatsMap.set(fieldName, fieldFormats.getInstance(formatConfig)); + formatsMap.set(fieldName, fieldFormats.getInstance(formatConfig.id, formatConfig.params)); } }); } From 9bb630067f60d8d23320466969f07c0029b33fdb Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Thu, 23 Jan 2020 15:19:12 +0300 Subject: [PATCH 04/13] fix PR comments --- .../search/search_source/search_source.ts | 7 +- .../components/metric_vis_component.tsx | 8 +-- .../public/metric_vis_type.test.ts | 4 +- .../public/components/vis_types/table/vis.js | 6 +- src/legacy/ui/public/agg_types/agg_config.ts | 10 +-- src/legacy/ui/public/agg_types/agg_type.ts | 10 +-- .../buckets/create_filter/date_range.test.ts | 5 +- .../buckets/create_filter/histogram.test.ts | 5 +- .../buckets/create_filter/ip_range.test.ts | 4 +- .../buckets/create_filter/range.test.ts | 5 +- .../ui/public/agg_types/buckets/date_range.ts | 14 ++-- .../ui/public/agg_types/buckets/ip_range.ts | 14 ++-- .../ui/public/agg_types/buckets/range.test.ts | 7 +- .../ui/public/agg_types/buckets/range.ts | 4 +- .../ui/public/agg_types/buckets/terms.ts | 8 +-- .../public/agg_types/metrics/cardinality.ts | 4 +- .../ui/public/agg_types/metrics/count.ts | 4 +- .../agg_types/metrics/metric_agg_type.ts | 6 +- .../agg_types/metrics/percentile_ranks.ts | 12 ++-- .../loader/pipeline_helpers/utilities.ts | 30 ++++----- ...{base_converters.ts => base_formatters.ts} | 4 +- .../common/field_formats/converters/custom.ts | 4 +- .../field_formats/converters/date_server.ts | 4 +- .../common/field_formats/converters/string.ts | 2 +- .../data/common/field_formats/field_format.ts | 17 ++--- .../field_formats_registry.test.ts | 65 ++++++++++--------- .../field_formats/field_formats_registry.ts | 30 ++++----- .../data/common/field_formats/index.ts | 15 +---- .../data/common/field_formats/static.ts | 28 ++++++++ .../data/common/field_formats/types.ts | 25 ++++++- src/plugins/data/common/types.ts | 1 - .../field_formats/field_formats_service.ts | 16 ++--- src/plugins/data/public/index.ts | 27 +------- .../public/index_patterns/fields/field.ts | 8 +-- .../index_patterns/format_hit.ts | 4 +- .../index_patterns/index_pattern.test.ts | 4 +- src/plugins/data/public/mocks.ts | 4 +- .../field_formats/field_formats_service.ts | 13 ++-- .../data/server/field_formats/index.ts | 1 - src/plugins/data/server/index.ts | 49 ++++---------- src/test_utils/public/stub_field_formats.ts | 8 +-- src/test_utils/public/stub_index_pattern.js | 9 +-- .../metric_expression.test.tsx | 11 ++-- .../csv/server/__tests__/execute_job.js | 8 +-- .../csv/server/lib/field_format_map.test.ts | 13 ++-- .../csv/server/lib/field_format_map.ts | 16 ++--- 46 files changed, 261 insertions(+), 292 deletions(-) rename src/plugins/data/common/field_formats/{base_converters.ts => base_formatters.ts} (92%) create mode 100644 src/plugins/data/common/field_formats/static.ts diff --git a/src/legacy/core_plugins/data/public/search/search_source/search_source.ts b/src/legacy/core_plugins/data/public/search/search_source/search_source.ts index e977db713ebaa..da623f2a269e1 100644 --- a/src/legacy/core_plugins/data/public/search/search_source/search_source.ts +++ b/src/legacy/core_plugins/data/public/search/search_source/search_source.ts @@ -73,7 +73,7 @@ import _ from 'lodash'; import { normalizeSortRequest } from './normalize_sort_request'; import { fetchSoon } from '../fetch'; import { fieldWildcardFilter } from '../../../../../../plugins/kibana_utils/public'; -import { getHighlightRequest, esFilters, esQuery } from '../../../../../../plugins/data/public'; +import { fieldFormats, esFilters, esQuery } from '../../../../../../plugins/data/public'; import { RequestFailure } from '../fetch/errors'; import { filterDocvalueFields } from './filter_docvalue_fields'; import { SearchSourceOptions, SearchSourceFields, SearchRequest } from './types'; @@ -389,7 +389,10 @@ export class SearchSource { body.query = esQuery.buildEsQuery(index, query, filters, esQueryConfigs); if (highlightAll && body.query) { - body.highlight = getHighlightRequest(body.query, getUiSettings().get('doc_table:highlight')); + body.highlight = fieldFormats.getHighlightRequest( + body.query, + getUiSettings().get('doc_table:highlight') + ); delete searchRequest.highlightAll; } diff --git a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx index f8398f5c83146..3a6d60a89e610 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx +++ b/src/legacy/core_plugins/vis_type_metric/public/components/metric_vis_component.tsx @@ -24,7 +24,7 @@ import { isColorDark } from '@elastic/eui'; import { getHeatmapColors, getFormat, Vis } from '../legacy_imports'; import { MetricVisValue } from './metric_vis_value'; -import { FieldFormat, ContentType } from '../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../plugins/data/public'; import { Context } from '../metric_vis_fn'; import { KibanaDatatable } from '../../../../../plugins/expressions/public'; import { VisParams, MetricVisMetric } from '../types'; @@ -100,9 +100,9 @@ export class MetricVisComponent extends Component { } private getFormattedValue = ( - fieldFormatter: FieldFormat, + fieldFormatter: fieldFormats.FieldFormat, value: any, - format: ContentType = 'text' + format: fieldFormats.ContentType = 'text' ) => { if (isNaN(value)) return '-'; return fieldFormatter.convert(value, format); @@ -119,7 +119,7 @@ export class MetricVisComponent extends Component { const metrics: MetricVisMetric[] = []; let bucketColumnId: string; - let bucketFormatter: FieldFormat; + let bucketFormatter: fieldFormats.FieldFormat; if (dimensions.bucket) { bucketColumnId = table.columns[dimensions.bucket.accessor].id; diff --git a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.test.ts b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.test.ts index 649959054416c..c2b7e6da3f7bd 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.test.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.test.ts @@ -24,7 +24,7 @@ import { npStart } from 'ui/new_platform'; import getStubIndexPattern from 'fixtures/stubbed_logstash_index_pattern'; import { Vis } from '../../visualizations/public'; -import { UrlFormat } from '../../../../plugins/data/public'; +import { fieldFormats } from '../../../../plugins/data/public'; import { setup as visualizationsSetup, start as visualizationsStart, @@ -39,7 +39,7 @@ describe('metric_vis - createMetricVisTypeDefinition', () => { beforeAll(() => { visualizationsSetup.types.createReactVisualization(metricVisTypeDefinition); (npStart.plugins.data.fieldFormats.getType as jest.Mock).mockImplementation(() => { - return UrlFormat; + return fieldFormats.UrlFormat; }); }); diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/vis_types/table/vis.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/vis_types/table/vis.js index 10fc34fccd2cc..a82d5bdb1588c 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/vis_types/table/vis.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/vis_types/table/vis.js @@ -26,7 +26,7 @@ import { calculateLabel } from '../../../../common/calculate_label'; import { isSortable } from './is_sortable'; import { EuiToolTip, EuiIcon } from '@elastic/eui'; import { replaceVars } from '../../lib/replace_vars'; -import { FIELD_FORMAT_IDS } from '../../../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../../../plugins/data/public'; import { FormattedMessage } from '@kbn/i18n/react'; import { METRIC_TYPES } from '../../../../common/metric_types'; @@ -49,8 +49,8 @@ export class TableVis extends Component { constructor(props) { super(props); - const fieldFormats = npStart.plugins.data.fieldFormats; - const DateFormat = fieldFormats.getType(FIELD_FORMAT_IDS.DATE); + const fieldFormatsService = npStart.plugins.data.fieldFormats; + const DateFormat = fieldFormatsService.getType(fieldFormats.FIELD_FORMAT_IDS.DATE); this.dateFormatter = new DateFormat({}, this.props.getConfig); } diff --git a/src/legacy/ui/public/agg_types/agg_config.ts b/src/legacy/ui/public/agg_types/agg_config.ts index 0edf782318862..c84f36d57eba9 100644 --- a/src/legacy/ui/public/agg_types/agg_config.ts +++ b/src/legacy/ui/public/agg_types/agg_config.ts @@ -33,7 +33,7 @@ import { AggGroupNames } from '../vis/editors/default/agg_groups'; import { writeParams } from './agg_params'; import { AggConfigs } from './agg_configs'; import { Schema } from '../vis/editors/default/schemas'; -import { ContentType, KBN_FIELD_TYPES } from '../../../../plugins/data/public'; +import { fieldFormats, KBN_FIELD_TYPES } from '../../../../plugins/data/public'; export interface AggConfigOptions { enabled: boolean; @@ -371,7 +371,7 @@ export class AggConfig { return this.aggConfigs.timeRange; } - fieldFormatter(contentType?: ContentType, defaultFormat?: any) { + fieldFormatter(contentType?: fieldFormats.ContentType, defaultFormat?: any) { const format = this.type && this.type.getFormat(this); if (format) { @@ -381,12 +381,12 @@ export class AggConfig { return this.fieldOwnFormatter(contentType, defaultFormat); } - fieldOwnFormatter(contentType?: ContentType, defaultFormat?: any) { - const fieldFormats = npStart.plugins.data.fieldFormats; + fieldOwnFormatter(contentType?: fieldFormats.ContentType, defaultFormat?: any) { + const fieldFormatsService = npStart.plugins.data.fieldFormats; const field = this.getField(); let format = field && field.format; if (!format) format = defaultFormat; - if (!format) format = fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.STRING); + if (!format) format = fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.STRING); return format.getConverterFor(contentType); } diff --git a/src/legacy/ui/public/agg_types/agg_type.ts b/src/legacy/ui/public/agg_types/agg_type.ts index 39be1983223bc..3e6bbe5874d00 100644 --- a/src/legacy/ui/public/agg_types/agg_type.ts +++ b/src/legacy/ui/public/agg_types/agg_type.ts @@ -28,7 +28,7 @@ import { ISearchSource } from '../courier'; import { Adapters } from '../inspector'; import { BaseParamType } from './param_types/base'; import { AggParamType } from '../agg_types/param_types/agg'; -import { KBN_FIELD_TYPES, FieldFormat } from '../../../../plugins/data/public'; +import { KBN_FIELD_TYPES, fieldFormats } from '../../../../plugins/data/public'; export interface AggTypeConfig< TAggConfig extends AggConfig = AggConfig, @@ -55,16 +55,16 @@ export interface AggTypeConfig< inspectorAdapters: Adapters, abortSignal?: AbortSignal ) => Promise; - getFormat?: (agg: TAggConfig) => FieldFormat; + getFormat?: (agg: TAggConfig) => fieldFormats.FieldFormat; getValue?: (agg: TAggConfig, bucket: any) => any; getKey?: (bucket: any, key: any, agg: TAggConfig) => any; } const getFormat = (agg: AggConfig) => { const field = agg.getField(); - const fieldFormats = npStart.plugins.data.fieldFormats; + const fieldFormatsService = npStart.plugins.data.fieldFormats; - return field ? field.format : fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.STRING); + return field ? field.format : fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.STRING); }; export class AggType< @@ -192,7 +192,7 @@ export class AggType< * @param {agg} agg - the agg to pick a format for * @return {FieldFormat} */ - getFormat: (agg: TAggConfig) => FieldFormat; + getFormat: (agg: TAggConfig) => fieldFormats.FieldFormat; getValue: (agg: TAggConfig, bucket: any) => any; diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/date_range.test.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/date_range.test.ts index ddb4102563a7c..9c2c4f72704f4 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/date_range.test.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/date_range.test.ts @@ -19,7 +19,7 @@ import moment from 'moment'; import { createFilterDateRange } from './date_range'; -import { DateFormat } from '../../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../../plugins/data/public'; import { AggConfigs } from '../../agg_configs'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; @@ -28,10 +28,11 @@ jest.mock('ui/new_platform'); describe('AggConfig Filters', () => { describe('Date range', () => { + const getConfig = (() => {}) as fieldFormats.GetConfigFn; const getAggConfigs = () => { const field = { name: '@timestamp', - format: new DateFormat({}, () => {}), + format: new fieldFormats.DateFormat({}, getConfig), }; const indexPattern = { diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/histogram.test.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/histogram.test.ts index d07cf84aef4d9..ef49636f9e0c1 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/histogram.test.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/histogram.test.ts @@ -20,16 +20,17 @@ import { createFilterHistogram } from './histogram'; import { AggConfigs } from '../../agg_configs'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; -import { BytesFormat } from '../../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../../plugins/data/public'; jest.mock('ui/new_platform'); describe('AggConfig Filters', () => { describe('histogram', () => { + const getConfig = (() => {}) as fieldFormats.GetConfigFn; const getAggConfigs = () => { const field = { name: 'bytes', - format: new BytesFormat({}, () => {}), + format: new fieldFormats.BytesFormat({}, getConfig), }; const indexPattern = { diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/ip_range.test.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/ip_range.test.ts index bf6b437f17cf2..a9eca3bbb7a56 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/ip_range.test.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/ip_range.test.ts @@ -19,7 +19,7 @@ import { createFilterIpRange } from './ip_range'; import { AggConfigs } from '../../agg_configs'; -import { IpFormat } from '../../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../../plugins/data/public'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; @@ -30,7 +30,7 @@ describe('AggConfig Filters', () => { const getAggConfigs = (aggs: Array>) => { const field = { name: 'ip', - format: IpFormat, + format: fieldFormats.IpFormat, }; const indexPattern = { diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/range.test.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/range.test.ts index dc02b773edc42..720e952c28821 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/range.test.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/range.test.ts @@ -18,7 +18,7 @@ */ import { createFilterRange } from './range'; -import { BytesFormat } from '../../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../../plugins/data/public'; import { AggConfigs } from '../../agg_configs'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; @@ -27,10 +27,11 @@ jest.mock('ui/new_platform'); describe('AggConfig Filters', () => { describe('range', () => { + const getConfig = (() => {}) as fieldFormats.GetConfigFn; const getAggConfigs = () => { const field = { name: 'bytes', - format: new BytesFormat({}, () => {}), + format: new fieldFormats.BytesFormat({}, getConfig), }; const indexPattern = { diff --git a/src/legacy/ui/public/agg_types/buckets/date_range.ts b/src/legacy/ui/public/agg_types/buckets/date_range.ts index ad54e95ffb7b1..4144765b15068 100644 --- a/src/legacy/ui/public/agg_types/buckets/date_range.ts +++ b/src/legacy/ui/public/agg_types/buckets/date_range.ts @@ -25,11 +25,7 @@ import { BucketAggType, IBucketAggConfig } from './_bucket_agg_type'; import { createFilterDateRange } from './create_filter/date_range'; import { DateRangesParamEditor } from '../../vis/editors/default/controls/date_ranges'; -import { - KBN_FIELD_TYPES, - TEXT_CONTEXT_TYPE, - FieldFormat, -} from '../../../../../plugins/data/public'; +import { KBN_FIELD_TYPES, fieldFormats } from '../../../../../plugins/data/public'; const dateRangeTitle = i18n.translate('common.ui.aggTypes.buckets.dateRangeTitle', { defaultMessage: 'Date Range', @@ -48,13 +44,13 @@ export const dateRangeBucketAgg = new BucketAggType({ return { from, to }; }, getFormat(agg) { - const fieldFormats = npStart.plugins.data.fieldFormats; + const fieldFormatsService = npStart.plugins.data.fieldFormats; const formatter = agg.fieldOwnFormatter( - TEXT_CONTEXT_TYPE, - fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.DATE) + fieldFormats.TEXT_CONTEXT_TYPE, + fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.DATE) ); - const DateRangeFormat = FieldFormat.from(function(range: DateRangeKey) { + const DateRangeFormat = fieldFormats.FieldFormat.from(function(range: DateRangeKey) { return convertDateRangeToString(range, formatter); }); return new DateRangeFormat(); diff --git a/src/legacy/ui/public/agg_types/buckets/ip_range.ts b/src/legacy/ui/public/agg_types/buckets/ip_range.ts index 609cd8adb5c39..e730970b9ea05 100644 --- a/src/legacy/ui/public/agg_types/buckets/ip_range.ts +++ b/src/legacy/ui/public/agg_types/buckets/ip_range.ts @@ -27,11 +27,7 @@ import { BUCKET_TYPES } from './bucket_agg_types'; // @ts-ignore import { createFilterIpRange } from './create_filter/ip_range'; -import { - KBN_FIELD_TYPES, - TEXT_CONTEXT_TYPE, - FieldFormat, -} from '../../../../../plugins/data/public'; +import { KBN_FIELD_TYPES, fieldFormats } from '../../../../../plugins/data/public'; const ipRangeTitle = i18n.translate('common.ui.aggTypes.buckets.ipRangeTitle', { defaultMessage: 'IPv4 Range', @@ -52,12 +48,12 @@ export const ipRangeBucketAgg = new BucketAggType({ return { type: 'range', from: bucket.from, to: bucket.to }; }, getFormat(agg) { - const fieldFormats = npStart.plugins.data.fieldFormats; + const fieldFormatsService = npStart.plugins.data.fieldFormats; const formatter = agg.fieldOwnFormatter( - TEXT_CONTEXT_TYPE, - fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.IP) + fieldFormats.TEXT_CONTEXT_TYPE, + fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.IP) ); - const IpRangeFormat = FieldFormat.from(function(range: IpRangeKey) { + const IpRangeFormat = fieldFormats.FieldFormat.from(function(range: IpRangeKey) { return convertIPRangeToString(range, formatter); }); return new IpRangeFormat(); diff --git a/src/legacy/ui/public/agg_types/buckets/range.test.ts b/src/legacy/ui/public/agg_types/buckets/range.test.ts index 5db7eb3c2d8e9..dd85c3b31939f 100644 --- a/src/legacy/ui/public/agg_types/buckets/range.test.ts +++ b/src/legacy/ui/public/agg_types/buckets/range.test.ts @@ -19,7 +19,7 @@ import { AggConfigs } from '../agg_configs'; import { BUCKET_TYPES } from './bucket_agg_types'; -import { NumberFormat } from '../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../plugins/data/public'; jest.mock('ui/new_platform'); @@ -44,14 +44,15 @@ const buckets = [ ]; describe('Range Agg', () => { + const getConfig = (() => {}) as fieldFormats.GetConfigFn; const getAggConfigs = () => { const field = { name: 'bytes', - format: new NumberFormat( + format: new fieldFormats.NumberFormat( { pattern: '0,0.[000] b', }, - () => {} + getConfig ), }; diff --git a/src/legacy/ui/public/agg_types/buckets/range.ts b/src/legacy/ui/public/agg_types/buckets/range.ts index 24757a607e005..7f93127d948ce 100644 --- a/src/legacy/ui/public/agg_types/buckets/range.ts +++ b/src/legacy/ui/public/agg_types/buckets/range.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { BucketAggType } from './_bucket_agg_type'; -import { FieldFormat, KBN_FIELD_TYPES } from '../../../../../plugins/data/public'; +import { fieldFormats, KBN_FIELD_TYPES } from '../../../../../plugins/data/public'; import { RangeKey } from './range_key'; import { RangesEditor } from './range_editor'; @@ -68,7 +68,7 @@ export const rangeBucketAgg = new BucketAggType({ let aggFormat = formats.get(agg); if (aggFormat) return aggFormat; - const RangeFormat = FieldFormat.from((range: any) => { + const RangeFormat = fieldFormats.FieldFormat.from((range: any) => { const format = agg.fieldOwnFormatter(); const gte = '\u2265'; const lt = '\u003c'; diff --git a/src/legacy/ui/public/agg_types/buckets/terms.ts b/src/legacy/ui/public/agg_types/buckets/terms.ts index c805e53eb2b91..09c64f3967a80 100644 --- a/src/legacy/ui/public/agg_types/buckets/terms.ts +++ b/src/legacy/ui/public/agg_types/buckets/terms.ts @@ -35,7 +35,7 @@ import { OtherBucketParamEditor } from '../../vis/editors/default/controls/other import { AggConfigs } from '../agg_configs'; import { Adapters } from '../../../../../plugins/inspector/public'; -import { ContentType, FieldFormat, KBN_FIELD_TYPES } from '../../../../../plugins/data/public'; +import { fieldFormats, KBN_FIELD_TYPES } from '../../../../../plugins/data/public'; // @ts-ignore import { Schemas } from '../../vis/editors/default/schemas'; @@ -69,9 +69,9 @@ export const termsBucketAgg = new BucketAggType({ const params = agg.params; return agg.getFieldDisplayName() + ': ' + params.order.text; }, - getFormat(bucket): FieldFormat { + getFormat(bucket): fieldFormats.FieldFormat { return { - getConverterFor: (type: ContentType) => { + getConverterFor: (type: fieldFormats.ContentType) => { return (val: any) => { if (val === '__other__') { return bucket.params.otherBucketLabel; @@ -83,7 +83,7 @@ export const termsBucketAgg = new BucketAggType({ return bucket.params.field.format.convert(val, type); }; }, - } as FieldFormat; + } as fieldFormats.FieldFormat; }, createFilter: createFilterTerms, postFlightRequest: async ( diff --git a/src/legacy/ui/public/agg_types/metrics/cardinality.ts b/src/legacy/ui/public/agg_types/metrics/cardinality.ts index 301ae2c80116c..c69ffae3b4871 100644 --- a/src/legacy/ui/public/agg_types/metrics/cardinality.ts +++ b/src/legacy/ui/public/agg_types/metrics/cardinality.ts @@ -37,9 +37,9 @@ export const cardinalityMetricAgg = new MetricAggType({ }); }, getFormat() { - const fieldFormats = npStart.plugins.data.fieldFormats; + const fieldFormatsService = npStart.plugins.data.fieldFormats; - return fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); + return fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); }, params: [ { diff --git a/src/legacy/ui/public/agg_types/metrics/count.ts b/src/legacy/ui/public/agg_types/metrics/count.ts index b5b844e8658d6..22a939cd9a3fd 100644 --- a/src/legacy/ui/public/agg_types/metrics/count.ts +++ b/src/legacy/ui/public/agg_types/metrics/count.ts @@ -35,9 +35,9 @@ export const countMetricAgg = new MetricAggType({ }); }, getFormat() { - const fieldFormats = npStart.plugins.data.fieldFormats; + const fieldFormatsService = npStart.plugins.data.fieldFormats; - return fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); + return fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); }, getValue(agg, bucket) { return bucket.doc_count; diff --git a/src/legacy/ui/public/agg_types/metrics/metric_agg_type.ts b/src/legacy/ui/public/agg_types/metrics/metric_agg_type.ts index 29499c5be84b8..5cd3dffb10b9d 100644 --- a/src/legacy/ui/public/agg_types/metrics/metric_agg_type.ts +++ b/src/legacy/ui/public/agg_types/metrics/metric_agg_type.ts @@ -74,9 +74,11 @@ export class MetricAggType { - const registeredFormats = npStart.plugins.data.fieldFormats; + const fieldFormatsService = npStart.plugins.data.fieldFormats; const field = agg.getField(); - return field ? field.format : registeredFormats.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); + return field + ? field.format + : fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); }); this.subtype = diff --git a/src/legacy/ui/public/agg_types/metrics/percentile_ranks.ts b/src/legacy/ui/public/agg_types/metrics/percentile_ranks.ts index 1a1d5bf04309f..436f9cd66764d 100644 --- a/src/legacy/ui/public/agg_types/metrics/percentile_ranks.ts +++ b/src/legacy/ui/public/agg_types/metrics/percentile_ranks.ts @@ -25,7 +25,7 @@ import { getResponseAggConfigClass, IResponseAggConfig } from './lib/get_respons import { getPercentileValue } from './percentiles_get_value'; import { METRIC_TYPES } from './metric_agg_types'; -import { FIELD_FORMAT_IDS, KBN_FIELD_TYPES } from '../../../../../plugins/data/public'; +import { fieldFormats, KBN_FIELD_TYPES } from '../../../../../plugins/data/public'; // required by the values editor @@ -35,10 +35,10 @@ const getFieldFormats = () => npStart.plugins.data.fieldFormats; const valueProps = { makeLabel(this: IPercentileRanksAggConfig) { - const fieldFormats = getFieldFormats(); + const fieldFormatsService = getFieldFormats(); const field = this.getField(); const format = - (field && field.format) || fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); + (field && field.format) || fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); const customLabel = this.getParam('customLabel'); const label = customLabel || this.getFieldDisplayName(); @@ -84,10 +84,10 @@ export const percentileRanksMetricAgg = new MetricAggType new ValueAggConfig(value)); }, getFormat() { - const fieldFormats = getFieldFormats(); + const fieldFormatsService = getFieldFormats(); return ( - fieldFormats.getInstance(FIELD_FORMAT_IDS.PERCENT) || - fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.NUMBER) + fieldFormatsService.getInstance(fieldFormats.FIELD_FORMAT_IDS.PERCENT) || + fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.NUMBER) ); }, getValue(agg, bucket) { diff --git a/src/legacy/ui/public/visualize/loader/pipeline_helpers/utilities.ts b/src/legacy/ui/public/visualize/loader/pipeline_helpers/utilities.ts index 0b99810a85afe..bde865f504fdb 100644 --- a/src/legacy/ui/public/visualize/loader/pipeline_helpers/utilities.ts +++ b/src/legacy/ui/public/visualize/loader/pipeline_helpers/utilities.ts @@ -22,8 +22,7 @@ import { identity } from 'lodash'; import { AggConfig, Vis } from 'ui/vis'; import { npStart } from 'ui/new_platform'; import { SerializedFieldFormat } from 'src/plugins/expressions/public'; - -import { IFieldFormatId, FieldFormat, ContentType } from '../../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../../plugins/data/public'; import { tabifyGetColumns } from '../../../agg_response/tabify/_get_columns'; import { DateRangeKey, convertDateRangeToString } from '../../../agg_types/buckets/date_range'; @@ -43,13 +42,16 @@ function isTermsFieldFormat( const getConfig = (key: string, defaultOverride?: any): any => npStart.core.uiSettings.get(key, defaultOverride); -const DefaultFieldFormat = FieldFormat.from(identity); +const DefaultFieldFormat = fieldFormats.FieldFormat.from(identity); -const getFieldFormat = (id?: IFieldFormatId, params: object = {}): FieldFormat => { - const fieldFormats = npStart.plugins.data.fieldFormats; +const getFieldFormat = ( + id?: fieldFormats.IFieldFormatId, + params: object = {} +): fieldFormats.FieldFormat => { + const fieldFormatsService = npStart.plugins.data.fieldFormats; if (id) { - const Format = fieldFormats.getType(id); + const Format = fieldFormatsService.getType(id); if (Format) { return new Format(params, getConfig); @@ -91,7 +93,7 @@ export const createFormat = (agg: AggConfig): SerializedFieldFormat => { return formats[agg.type.name] ? formats[agg.type.name]() : format; }; -export type FormatFactory = (mapping?: SerializedFieldFormat) => FieldFormat; +export type FormatFactory = (mapping?: SerializedFieldFormat) => fieldFormats.FieldFormat; export const getFormat: FormatFactory = mapping => { if (!mapping) { @@ -99,7 +101,7 @@ export const getFormat: FormatFactory = mapping => { } const { id } = mapping; if (id === 'range') { - const RangeFormat = FieldFormat.from((range: any) => { + const RangeFormat = fieldFormats.FieldFormat.from((range: any) => { const format = getFieldFormat(id, mapping.params); const gte = '\u2265'; const lt = '\u003c'; @@ -116,21 +118,21 @@ export const getFormat: FormatFactory = mapping => { return new RangeFormat(); } else if (id === 'date_range') { const nestedFormatter = mapping.params as SerializedFieldFormat; - const DateRangeFormat = FieldFormat.from((range: DateRangeKey) => { + const DateRangeFormat = fieldFormats.FieldFormat.from((range: DateRangeKey) => { const format = getFieldFormat(nestedFormatter.id, nestedFormatter.params); return convertDateRangeToString(range, format.convert.bind(format)); }); return new DateRangeFormat(); } else if (id === 'ip_range') { const nestedFormatter = mapping.params as SerializedFieldFormat; - const IpRangeFormat = FieldFormat.from((range: IpRangeKey) => { + const IpRangeFormat = fieldFormats.FieldFormat.from((range: IpRangeKey) => { const format = getFieldFormat(nestedFormatter.id, nestedFormatter.params); return convertIPRangeToString(range, format.convert.bind(format)); }); return new IpRangeFormat(); } else if (isTermsFieldFormat(mapping) && mapping.params) { const { params } = mapping; - const convert = (val: string, type: ContentType) => { + const convert = (val: string, type: fieldFormats.ContentType) => { const format = getFieldFormat(params.id, mapping.params); if (val === '__other__') { @@ -145,8 +147,8 @@ export const getFormat: FormatFactory = mapping => { return { convert, - getConverterFor: (type: ContentType) => (val: string) => convert(val, type), - } as FieldFormat; + getConverterFor: (type: fieldFormats.ContentType) => (val: string) => convert(val, type), + } as fieldFormats.FieldFormat; } else { return getFieldFormat(id, mapping.params); } @@ -159,5 +161,3 @@ export const getTableAggs = (vis: Vis): AggConfig[] => { const columns = tabifyGetColumns(vis.aggs.getResponseAggs(), !vis.isHierarchical()); return columns.map(c => c.aggConfig); }; - -export { FieldFormat }; diff --git a/src/plugins/data/common/field_formats/base_converters.ts b/src/plugins/data/common/field_formats/base_formatters.ts similarity index 92% rename from src/plugins/data/common/field_formats/base_converters.ts rename to src/plugins/data/common/field_formats/base_formatters.ts index 686c53a0f46c2..6b6e9fafbe64b 100644 --- a/src/plugins/data/common/field_formats/base_converters.ts +++ b/src/plugins/data/common/field_formats/base_formatters.ts @@ -17,7 +17,7 @@ * under the License. */ -import { IFieldFormatType } from './field_format'; +import { IFieldFormatType } from './types'; import { BoolFormat, @@ -37,7 +37,7 @@ import { UrlFormat, } from './converters'; -export const baseConverters: IFieldFormatType[] = [ +export const baseFormatters: IFieldFormatType[] = [ BoolFormat, BytesFormat, ColorFormat, diff --git a/src/plugins/data/common/field_formats/converters/custom.ts b/src/plugins/data/common/field_formats/converters/custom.ts index 1c17e231cace8..a1ce0cf3e7b54 100644 --- a/src/plugins/data/common/field_formats/converters/custom.ts +++ b/src/plugins/data/common/field_formats/converters/custom.ts @@ -17,8 +17,8 @@ * under the License. */ -import { FieldFormat, IFieldFormatType } from '../field_format'; -import { TextContextTypeConvert, FIELD_FORMAT_IDS } from '../types'; +import { FieldFormat } from '../field_format'; +import { TextContextTypeConvert, FIELD_FORMAT_IDS, IFieldFormatType } from '../types'; export const createCustomFieldFormat = (convert: TextContextTypeConvert): IFieldFormatType => class CustomFieldFormat extends FieldFormat { diff --git a/src/plugins/data/common/field_formats/converters/date_server.ts b/src/plugins/data/common/field_formats/converters/date_server.ts index 34278ea9fe641..acd8a027614af 100644 --- a/src/plugins/data/common/field_formats/converters/date_server.ts +++ b/src/plugins/data/common/field_formats/converters/date_server.ts @@ -21,7 +21,7 @@ import { memoize, noop } from 'lodash'; import moment from 'moment-timezone'; import { KBN_FIELD_TYPES } from '../../kbn_field_types/types'; import { FieldFormat, IFieldFormatMetaParams } from '../field_format'; -import { TextContextTypeConvert, FIELD_FORMAT_IDS } from '../types'; +import { TextContextTypeConvert, FIELD_FORMAT_IDS, GetConfigFn } from '../types'; export class DateFormat extends FieldFormat { static id = FIELD_FORMAT_IDS.DATE; @@ -32,7 +32,7 @@ export class DateFormat extends FieldFormat { private memoizedPattern: string = ''; private timeZone: string = ''; - constructor(params: IFieldFormatMetaParams, getConfig: Function) { + constructor(params: IFieldFormatMetaParams, getConfig: GetConfigFn) { super(params, getConfig); this.memoizedConverter = memoize((val: any) => { diff --git a/src/plugins/data/common/field_formats/converters/string.ts b/src/plugins/data/common/field_formats/converters/string.ts index b2d92cf475a16..1a095d4fd3cfd 100644 --- a/src/plugins/data/common/field_formats/converters/string.ts +++ b/src/plugins/data/common/field_formats/converters/string.ts @@ -18,7 +18,7 @@ */ import { i18n } from '@kbn/i18n'; -import { asPrettyString } from '../index'; +import { asPrettyString } from '../utils'; import { KBN_FIELD_TYPES } from '../../kbn_field_types/types'; import { FieldFormat } from '../field_format'; import { TextContextTypeConvert, FIELD_FORMAT_IDS } from '../types'; diff --git a/src/plugins/data/common/field_formats/field_format.ts b/src/plugins/data/common/field_formats/field_format.ts index a0621b27f5bc0..c63dd4a6f558a 100644 --- a/src/plugins/data/common/field_formats/field_format.ts +++ b/src/plugins/data/common/field_formats/field_format.ts @@ -20,8 +20,9 @@ import { transform, size, cloneDeep, get, defaults } from 'lodash'; import { createCustomFieldFormat } from './converters/custom'; import { + GetConfigFn, ContentType, - FIELD_FORMAT_IDS, + IFieldFormatType, FieldFormatConvert, FieldFormatConvertFunction, HtmlContextTypeOptions, @@ -97,9 +98,9 @@ export abstract class FieldFormat { public type: any = this.constructor; protected readonly _params: any; - protected getConfig: Function | undefined; + protected getConfig: GetConfigFn | undefined; - constructor(_params: IFieldFormatMetaParams = {}, getConfig?: Function) { + constructor(_params: IFieldFormatMetaParams = {}, getConfig?: GetConfigFn) { this._params = _params; if (getConfig) { @@ -226,13 +227,3 @@ export abstract class FieldFormat { return Boolean(fieldFormat && fieldFormat.convert); } } - -export type IFieldFormat = PublicMethodsOf; -/** - * @string id type is needed for creating custom converters. - */ -export type IFieldFormatId = FIELD_FORMAT_IDS | string; -export type IFieldFormatType = (new (params?: any, getConfig?: Function) => FieldFormat) & { - id: IFieldFormatId; - fieldType: string | string[]; -}; diff --git a/src/plugins/data/common/field_formats/field_formats_registry.test.ts b/src/plugins/data/common/field_formats/field_formats_registry.test.ts index c41c90a4295ed..ff3573c8992be 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.test.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.test.ts @@ -16,21 +16,22 @@ * specific language governing permissions and limitations * under the License. */ -import { FieldFormatRegisty } from './field_formats_registry'; +import { FieldFormatRegistry } from './field_formats_registry'; import { BoolFormat, PercentFormat, StringFormat } from './converters'; import { IFieldFormatType } from './field_format'; +import { GetConfigFn } from './types'; import { KBN_FIELD_TYPES } from '../../common'; const getValueOfPrivateField = (instance: any, field: string) => instance[field]; -describe('FieldFormatRegisty', () => { - let fieldFormatRegisty: FieldFormatRegisty; +describe('FieldFormatRegistry', () => { + let fieldFormatRegistry: FieldFormatRegistry; let defaultMap = {}; - const getConfig = (key: string) => defaultMap; + const getConfig = (() => {}) as GetConfigFn; beforeEach(() => { - fieldFormatRegisty = new FieldFormatRegisty(); - fieldFormatRegisty.init( + fieldFormatRegistry = new FieldFormatRegistry(); + fieldFormatRegistry.init( getConfig, { parsedUrl: { @@ -43,17 +44,17 @@ describe('FieldFormatRegisty', () => { ); }); - test('should allows to create an instance of "FieldFormatRegisty"', () => { - expect(fieldFormatRegisty).toBeDefined(); + test('should allows to create an instance of "FieldFormatRegistry"', () => { + expect(fieldFormatRegistry).toBeDefined(); - expect(getValueOfPrivateField(fieldFormatRegisty, 'fieldFormats')).toBeDefined(); - expect(getValueOfPrivateField(fieldFormatRegisty, 'defaultMap')).toEqual({}); + expect(getValueOfPrivateField(fieldFormatRegistry, 'fieldFormats')).toBeDefined(); + expect(getValueOfPrivateField(fieldFormatRegistry, 'defaultMap')).toEqual({}); }); describe('init', () => { test('should provide an public "init" method', () => { - expect(fieldFormatRegisty.init).toBeDefined(); - expect(typeof fieldFormatRegisty.init).toBe('function'); + expect(fieldFormatRegistry.init).toBeDefined(); + expect(typeof fieldFormatRegistry.init).toBe('function'); }); test('should populate the "defaultMap" object', () => { @@ -61,22 +62,22 @@ describe('FieldFormatRegisty', () => { number: { id: 'number', params: {} }, }; - fieldFormatRegisty.init(getConfig, {}, []); - expect(getValueOfPrivateField(fieldFormatRegisty, 'defaultMap')).toEqual(defaultMap); + fieldFormatRegistry.init(getConfig, {}, []); + expect(getValueOfPrivateField(fieldFormatRegistry, 'defaultMap')).toEqual(defaultMap); }); }); describe('register', () => { test('should provide an public "register" method', () => { - expect(fieldFormatRegisty.register).toBeDefined(); - expect(typeof fieldFormatRegisty.register).toBe('function'); + expect(fieldFormatRegistry.register).toBeDefined(); + expect(typeof fieldFormatRegistry.register).toBe('function'); }); test('should register field formats', () => { - fieldFormatRegisty.register([StringFormat, BoolFormat]); + fieldFormatRegistry.register([StringFormat, BoolFormat]); const registeredFieldFormatters: Map = getValueOfPrivateField( - fieldFormatRegisty, + fieldFormatRegistry, 'fieldFormats' ); @@ -90,28 +91,28 @@ describe('FieldFormatRegisty', () => { describe('getType', () => { test('should provide an public "getType" method', () => { - expect(fieldFormatRegisty.getType).toBeDefined(); - expect(typeof fieldFormatRegisty.getType).toBe('function'); + expect(fieldFormatRegistry.getType).toBeDefined(); + expect(typeof fieldFormatRegistry.getType).toBe('function'); }); test('should return the registered type of the field format by identifier', () => { - fieldFormatRegisty.register([StringFormat]); + fieldFormatRegistry.register([StringFormat]); - expect(fieldFormatRegisty.getType(StringFormat.id)).toBeDefined(); + expect(fieldFormatRegistry.getType(StringFormat.id)).toBeDefined(); }); test('should return void if the field format type has not been registered', () => { - fieldFormatRegisty.register([BoolFormat]); + fieldFormatRegistry.register([BoolFormat]); - expect(fieldFormatRegisty.getType(StringFormat.id)).toBeUndefined(); + expect(fieldFormatRegistry.getType(StringFormat.id)).toBeUndefined(); }); }); describe('fieldFormatMetaParamsDecorator', () => { test('should set meta params for all instances of FieldFormats', () => { - fieldFormatRegisty.register([StringFormat]); + fieldFormatRegistry.register([StringFormat]); - const DecoratedStingFormat = fieldFormatRegisty.getType(StringFormat.id); + const DecoratedStingFormat = fieldFormatRegistry.getType(StringFormat.id); expect(DecoratedStingFormat).toBeDefined(); @@ -130,9 +131,9 @@ describe('FieldFormatRegisty', () => { }); test('should decorate static fields', () => { - fieldFormatRegisty.register([BoolFormat]); + fieldFormatRegistry.register([BoolFormat]); - const DecoratedBoolFormat = fieldFormatRegisty.getType(BoolFormat.id); + const DecoratedBoolFormat = fieldFormatRegistry.getType(BoolFormat.id); expect(DecoratedBoolFormat).toBeDefined(); @@ -145,14 +146,14 @@ describe('FieldFormatRegisty', () => { describe('getByFieldType', () => { test('should provide an public "getByFieldType" method', () => { - expect(fieldFormatRegisty.getByFieldType).toBeDefined(); - expect(typeof fieldFormatRegisty.getByFieldType).toBe('function'); + expect(fieldFormatRegistry.getByFieldType).toBeDefined(); + expect(typeof fieldFormatRegistry.getByFieldType).toBe('function'); }); test('should decorate returns types', () => { - fieldFormatRegisty.register([StringFormat, BoolFormat]); + fieldFormatRegistry.register([StringFormat, BoolFormat]); - const [DecoratedStringFormat] = fieldFormatRegisty.getByFieldType(KBN_FIELD_TYPES.STRING); + const [DecoratedStringFormat] = fieldFormatRegistry.getByFieldType(KBN_FIELD_TYPES.STRING); expect(DecoratedStringFormat).toBeDefined(); diff --git a/src/plugins/data/common/field_formats/field_formats_registry.ts b/src/plugins/data/common/field_formats/field_formats_registry.ts index e6eebd65ea514..68707ce55b1f7 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.ts @@ -20,34 +20,28 @@ // eslint-disable-next-line max-classes-per-file import { forOwn, isFunction, memoize } from 'lodash'; +import { ES_FIELD_TYPES, KBN_FIELD_TYPES } from '../../common'; + import { - ES_FIELD_TYPES, - KBN_FIELD_TYPES, + GetConfigFn, + IFieldFormatConfig, FIELD_FORMAT_IDS, IFieldFormatType, IFieldFormatId, - FieldFormat, - IFieldFormatMetaParams, -} from '../../common'; - -import { baseConverters } from './base_converters'; - -export interface IFieldFormatConfig { - id: IFieldFormatId; - params: Record; - es?: boolean; -} +} from './types'; +import { baseFormatters } from './base_formatters'; +import { FieldFormat, IFieldFormatMetaParams } from './field_format'; -export class FieldFormatRegisty { +export class FieldFormatRegistry { protected fieldFormats: Map = new Map(); protected defaultMap: Record = {}; protected metaParamsOptions: Record = {}; - protected getConfig?: Function; + protected getConfig?: GetConfigFn; init( - getConfig: Function, + getConfig: GetConfigFn, metaParamsOptions: Record = {}, - defaultFieldConverters: IFieldFormatType[] = baseConverters + defaultFieldConverters: IFieldFormatType[] = baseFormatters ) { const defaultTypeMap = getConfig('format:defaultTypeMap'); @@ -251,7 +245,7 @@ export class FieldFormatRegisty { static id = fieldFormat.id; static fieldType = fieldFormat.fieldType; - constructor(params: Record = {}, getConfig?: Function) { + constructor(params: Record = {}, getConfig?: GetConfigFn) { super(getMetaParams(params), getConfig); } }; diff --git a/src/plugins/data/common/field_formats/index.ts b/src/plugins/data/common/field_formats/index.ts index 4b55eac7064ae..e54903375dcf1 100644 --- a/src/plugins/data/common/field_formats/index.ts +++ b/src/plugins/data/common/field_formats/index.ts @@ -17,15 +17,6 @@ * under the License. */ -export { HTML_CONTEXT_TYPE, TEXT_CONTEXT_TYPE } from './content_types'; -export { - FieldFormat, - IFieldFormatType, - IFieldFormatId, - IFieldFormatMetaParams, -} from './field_format'; -export { FieldFormatRegisty, IFieldFormatConfig } from './field_formats_registry'; -export { getHighlightRequest, asPrettyString, getHighlightHtml } from './utils'; -export { baseConverters } from './base_converters'; -export * from './converters'; -export * from './constants'; +import * as fieldFormats from './static'; + +export { fieldFormats }; diff --git a/src/plugins/data/common/field_formats/static.ts b/src/plugins/data/common/field_formats/static.ts new file mode 100644 index 0000000000000..2286366dc3f48 --- /dev/null +++ b/src/plugins/data/common/field_formats/static.ts @@ -0,0 +1,28 @@ +/* + * 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 { HTML_CONTEXT_TYPE, TEXT_CONTEXT_TYPE } from './content_types'; +export { FieldFormat, IFieldFormatMetaParams } from './field_format'; +export { FieldFormatRegistry } from './field_formats_registry'; +export { getHighlightRequest, asPrettyString, getHighlightHtml } from './utils'; +export { baseFormatters } from './base_formatters'; + +export * from './converters'; +export * from './constants'; +export * from './types'; diff --git a/src/plugins/data/common/field_formats/types.ts b/src/plugins/data/common/field_formats/types.ts index dce3c66b0f886..5c6e38aeaa43d 100644 --- a/src/plugins/data/common/field_formats/types.ts +++ b/src/plugins/data/common/field_formats/types.ts @@ -17,11 +17,10 @@ * under the License. */ -/** @public **/ -export type ContentType = 'html' | 'text'; +import { FieldFormat } from './field_format'; /** @public **/ -export { IFieldFormat } from './field_format'; +export type ContentType = 'html' | 'text'; /** @internal **/ export interface HtmlContextTypeOptions { @@ -66,3 +65,23 @@ export enum FIELD_FORMAT_IDS { TRUNCATE = 'truncate', URL = 'url', } + +export interface IFieldFormatConfig { + id: IFieldFormatId; + params: Record; + es?: boolean; +} + +export type GetConfigFn = (key: string, defaultOverride?: T) => T; + +export type IFieldFormat = PublicMethodsOf; + +/** + * @string id type is needed for creating custom converters. + */ +export type IFieldFormatId = FIELD_FORMAT_IDS | string; + +export type IFieldFormatType = (new (params?: any, getConfig?: GetConfigFn) => FieldFormat) & { + id: IFieldFormatId; + fieldType: string | string[]; +}; diff --git a/src/plugins/data/common/types.ts b/src/plugins/data/common/types.ts index bc0d0c323bafa..be0d3230b3a0e 100644 --- a/src/plugins/data/common/types.ts +++ b/src/plugins/data/common/types.ts @@ -17,7 +17,6 @@ * under the License. */ -export * from './field_formats/types'; export * from './timefilter/types'; export * from './query/types'; export * from './kbn_field_types/types'; diff --git a/src/plugins/data/public/field_formats/field_formats_service.ts b/src/plugins/data/public/field_formats/field_formats_service.ts index 26846efd66885..081b1d50ca5eb 100644 --- a/src/plugins/data/public/field_formats/field_formats_service.ts +++ b/src/plugins/data/public/field_formats/field_formats_service.ts @@ -18,19 +18,19 @@ */ import { CoreSetup } from 'src/core/public'; -import { FieldFormatRegisty } from '../../common/field_formats'; +import { fieldFormats } from '../../common/field_formats'; export class FieldFormatsService { - private readonly fieldFormats: FieldFormatRegisty = new FieldFormatRegisty(); + private readonly fieldFormatsRegistry: fieldFormats.FieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); public setup(core: CoreSetup) { core.uiSettings.getUpdate$().subscribe(({ key, newValue }) => { if (key === 'format:defaultTypeMap') { - this.fieldFormats.parseDefaultTypeMap(newValue); + this.fieldFormatsRegistry.parseDefaultTypeMap(newValue); } }); - this.fieldFormats.init(core.uiSettings.get, { + this.fieldFormatsRegistry.init(core.uiSettings.get, { parsedUrl: { origin: window.location.origin, pathname: window.location.pathname, @@ -38,16 +38,16 @@ export class FieldFormatsService { }, }); - return this.fieldFormats as FieldFormatsSetup; + return this.fieldFormatsRegistry as FieldFormatsSetup; } public start() { - return this.fieldFormats as FieldFormatsStart; + return this.fieldFormatsRegistry as FieldFormatsStart; } } /** @public */ -export type FieldFormatsSetup = Omit; +export type FieldFormatsSetup = Pick; /** @public */ -export type FieldFormatsStart = Omit; +export type FieldFormatsStart = Omit; diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index 5d33b131430c0..ddf398c830376 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -31,13 +31,6 @@ export function plugin(initializerContext: PluginInitializerContext) { export { IRequestTypesMap, IResponseTypesMap } from './search'; export * from './types'; export { - // field formats - ContentType, // only used in agg_type - FIELD_FORMAT_IDS, - IFieldFormat, - IFieldFormatId, - IFieldFormatType, - FieldFormatRegisty, // index patterns IIndexPattern, IFieldType, @@ -62,26 +55,8 @@ export { esFilters, esKuery, esQuery, + fieldFormats, // field formats - BoolFormat, - BytesFormat, - ColorFormat, - DateFormat, - DateNanosFormat, - DEFAULT_CONVERTER_COLOR, - DurationFormat, - FieldFormat, - getHighlightRequest, // only used in search source - IpFormat, - NumberFormat, - PercentFormat, - RelativeDateFormat, - SourceFormat, - StaticLookupFormat, - StringFormat, - TEXT_CONTEXT_TYPE, // only used in agg_types - TruncateFormat, - UrlFormat, // index patterns isFilterable, // kbn field types diff --git a/src/plugins/data/public/index_patterns/fields/field.ts b/src/plugins/data/public/index_patterns/fields/field.ts index 6ed3c2be8f96e..730a2f88c5eb7 100644 --- a/src/plugins/data/public/index_patterns/fields/field.ts +++ b/src/plugins/data/public/index_patterns/fields/field.ts @@ -26,7 +26,7 @@ import { IFieldType, getKbnFieldType, IFieldSubType, - FieldFormat, + fieldFormats, shortenDottedString, } from '../../../common'; @@ -95,12 +95,12 @@ export class Field implements IFieldType { let format = spec.format; - if (!FieldFormat.isInstanceOfFieldFormat(format)) { - const fieldFormats = getFieldFormats(); + if (!fieldFormats.FieldFormat.isInstanceOfFieldFormat(format)) { + const fieldFormatsService = getFieldFormats(); format = indexPattern.fieldFormatMap[spec.name] || - fieldFormats.getDefaultInstance(spec.type, spec.esTypes); + fieldFormatsService.getDefaultInstance(spec.type, spec.esTypes); } const indexed = !!spec.indexed; diff --git a/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts b/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts index 59ee18b3dcb50..f9e15c8650ce0 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts @@ -19,7 +19,7 @@ import _ from 'lodash'; import { IndexPattern } from './index_pattern'; -import { ContentType } from '../../../common'; +import { fieldFormats } from '../../../common'; const formattedCache = new WeakMap(); const partialFormattedCache = new WeakMap(); @@ -31,7 +31,7 @@ export function formatHitProvider(indexPattern: IndexPattern, defaultFormat: any hit: Record, val: any, fieldName: string, - type: ContentType = 'html' + type: fieldFormats.ContentType = 'html' ) { const field = indexPattern.fields.getByName(fieldName); const format = field ? field.format : defaultFormat; diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts index 10963a54a9abb..650d2d3a425b1 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts @@ -31,7 +31,7 @@ import { setNotifications, setFieldFormats } from '../../services'; // Temporary disable eslint, will be removed after moving to new platform folder // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { notificationServiceMock } from '../../../../../core/public/notifications/notifications_service.mock'; -import { FieldFormatRegisty } from '../../../common/field_formats'; +import { fieldFormats } from '../../../common/field_formats'; jest.mock('../../../../kibana_utils/public', () => { const originalModule = jest.requireActual('../../../../kibana_utils/public'); @@ -125,7 +125,7 @@ describe('IndexPattern', () => { setNotifications(notifications); setFieldFormats(({ getDefaultInstance: jest.fn(), - } as unknown) as FieldFormatRegisty); + } as unknown) as fieldFormats.FieldFormatRegistry); return create(indexPatternId).then((pattern: IndexPattern) => { indexPattern = pattern; diff --git a/src/plugins/data/public/mocks.ts b/src/plugins/data/public/mocks.ts index cf54d77d19964..a98775241159c 100644 --- a/src/plugins/data/public/mocks.ts +++ b/src/plugins/data/public/mocks.ts @@ -17,11 +17,11 @@ * under the License. */ import { - FieldFormatRegisty, Plugin, FieldFormatsStart, FieldFormatsSetup, IndexPatternsContract, + fieldFormats, } from '.'; import { searchSetupMock } from './search/mocks'; import { queryServiceMock } from './query/mocks'; @@ -35,7 +35,7 @@ const autocompleteMock: any = { hasQuerySuggestions: jest.fn(), }; -const fieldFormatsMock: PublicMethodsOf = { +const fieldFormatsMock: PublicMethodsOf = { getByFieldType: jest.fn(), getDefaultConfig: jest.fn(), getDefaultInstance: jest.fn() as any, diff --git a/src/plugins/data/server/field_formats/field_formats_service.ts b/src/plugins/data/server/field_formats/field_formats_service.ts index 076fca7fbf778..05b7986e60dad 100644 --- a/src/plugins/data/server/field_formats/field_formats_service.ts +++ b/src/plugins/data/server/field_formats/field_formats_service.ts @@ -17,15 +17,16 @@ * under the License. */ import { has } from 'lodash'; -import { FieldFormatRegisty, IFieldFormatType, baseConverters } from '../../common/field_formats'; +import { fieldFormats } from '../../common/field_formats'; import { IUiSettingsClient } from '../../../../core/server'; export class FieldFormatsService { - private readonly fieldFormatClasses: IFieldFormatType[] = baseConverters; + private readonly fieldFormatClasses: fieldFormats.IFieldFormatType[] = + fieldFormats.baseFormatters; public setup() { return { - register: (customFieldFormat: IFieldFormatType) => + register: (customFieldFormat: fieldFormats.IFieldFormatType) => this.fieldFormatClasses.push(customFieldFormat), }; } @@ -33,7 +34,7 @@ export class FieldFormatsService { public start() { return { fieldFormatServiceFactory: async (uiSettings: IUiSettingsClient) => { - const fieldFormats = new FieldFormatRegisty(); + const fieldFormatsRegistry = new fieldFormats.FieldFormatRegistry(); const uiConfigs = await uiSettings.getAll(); const registeredUiSettings = uiSettings.getRegistered(); @@ -43,9 +44,9 @@ export class FieldFormatsService { } }); - fieldFormats.init((key: string) => uiConfigs[key], {}, this.fieldFormatClasses); + fieldFormatsRegistry.init((key: string) => uiConfigs[key], {}, this.fieldFormatClasses); - return fieldFormats; + return fieldFormatsRegistry; }, }; } diff --git a/src/plugins/data/server/field_formats/index.ts b/src/plugins/data/server/field_formats/index.ts index 168e112d86b75..4550a5781535f 100644 --- a/src/plugins/data/server/field_formats/index.ts +++ b/src/plugins/data/server/field_formats/index.ts @@ -18,4 +18,3 @@ */ export { FieldFormatsService, FieldFormatsSetup, FieldFormatsStart } from './field_formats_service'; -export { FieldFormatRegisty } from '../../common/field_formats'; diff --git a/src/plugins/data/server/index.ts b/src/plugins/data/server/index.ts index e14ba90e7357d..d7754928099c8 100644 --- a/src/plugins/data/server/index.ts +++ b/src/plugins/data/server/index.ts @@ -29,16 +29,20 @@ export function plugin(initializerContext: PluginInitializerContext) { * @public */ export { IRequestTypesMap, IResponseTypesMap } from './search'; + export { - // field formats - FIELD_FORMAT_IDS, - IFieldFormat, - IFieldFormatId, - IFieldFormatType, - IFieldFormatConfig, - FieldFormatRegisty, + // es query + esFilters, + esKuery, + esQuery, + fieldFormats, + // kbn field types + castEsToKbnFieldTypeName, + getKbnFieldType, + getKbnTypeNames, // index patterns IIndexPattern, + isFilterable, IFieldType, IFieldSubType, // kbn field types @@ -63,37 +67,8 @@ export { shouldReadFieldFromDocValues, indexPatterns, } from './index_patterns'; + export * from './search'; -export { - // es query - esFilters, - esKuery, - esQuery, - // field formats - BoolFormat, - BytesFormat, - ColorFormat, - DateFormat, - DateNanosFormat, - DEFAULT_CONVERTER_COLOR, - DurationFormat, - FieldFormat, - IpFormat, - NumberFormat, - PercentFormat, - RelativeDateFormat, - SourceFormat, - StaticLookupFormat, - StringFormat, - TruncateFormat, - UrlFormat, - // index patterns - isFilterable, - // kbn field types - castEsToKbnFieldTypeName, - getKbnFieldType, - getKbnTypeNames, -} from '../common'; export { DataServerPlugin as Plugin, diff --git a/src/test_utils/public/stub_field_formats.ts b/src/test_utils/public/stub_field_formats.ts index 5244569b1de59..42a2d36da112d 100644 --- a/src/test_utils/public/stub_field_formats.ts +++ b/src/test_utils/public/stub_field_formats.ts @@ -17,12 +17,12 @@ * under the License. */ import { CoreSetup } from 'kibana/public'; -import { FieldFormatRegisty } from '../../plugins/data/public'; +import { fieldFormats } from '../../plugins/data/public'; export const getFieldFormatsRegistry = (core: CoreSetup) => { - const fieldFormats = new FieldFormatRegisty(); + const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); - fieldFormats.init(core.uiSettings.get, {}); + fieldFormatRegistry.init(core.uiSettings.get, {}); - return fieldFormats; + return fieldFormatRegistry; }; diff --git a/src/test_utils/public/stub_index_pattern.js b/src/test_utils/public/stub_index_pattern.js index 7807821ab09bd..9e1ad23602a01 100644 --- a/src/test_utils/public/stub_index_pattern.js +++ b/src/test_utils/public/stub_index_pattern.js @@ -22,12 +22,7 @@ import sinon from 'sinon'; // because it is one of the few places that we need to access the IndexPattern class itself, rather // than just the type. Doing this as a temporary measure; it will be left behind when migrating to NP. -import { - FieldList, - FIELD_FORMAT_IDS, - IndexPattern, - indexPatterns, -} from '../../plugins/data/public'; +import { FieldList, fieldFormats, IndexPattern, indexPatterns } from '../../plugins/data/public'; import { setFieldFormats } from '../../plugins/data/public/services'; @@ -61,7 +56,7 @@ export default function StubIndexPattern(pattern, getConfig, timeField, fields, this.flattenHit = indexPatterns.flattenHitWrapper(this, this.metaFields); this.formatHit = indexPatterns.formatHitProvider( this, - registeredFieldFormats.getDefaultInstance(FIELD_FORMAT_IDS.STRING) + registeredFieldFormats.getDefaultInstance(fieldFormats.FIELD_FORMAT_IDS.STRING) ); this.fieldsFetcher = { apiClient: { baseUrl: '' } }; this.formatField = this.formatHit.formatField; diff --git a/x-pack/legacy/plugins/lens/public/metric_visualization_plugin/metric_expression.test.tsx b/x-pack/legacy/plugins/lens/public/metric_visualization_plugin/metric_expression.test.tsx index 9220c3ec75fad..a9a48c46f5bd0 100644 --- a/x-pack/legacy/plugins/lens/public/metric_visualization_plugin/metric_expression.test.tsx +++ b/x-pack/legacy/plugins/lens/public/metric_visualization_plugin/metric_expression.test.tsx @@ -9,7 +9,7 @@ import { LensMultiTable } from '../types'; import React from 'react'; import { shallow } from 'enzyme'; import { MetricConfig } from './types'; -import { FieldFormat } from '../../../../../../src/plugins/data/public'; +import { fieldFormats } from '../../../../../../src/plugins/data/public'; function sampleArgs() { const data: LensMultiTable = { @@ -54,8 +54,11 @@ describe('metric_expression', () => { test('it renders the title and value', () => { const { data, args } = sampleArgs(); - expect(shallow( x as FieldFormat} />)) - .toMatchInlineSnapshot(` + expect( + shallow( + x as fieldFormats.FieldFormat} /> + ) + ).toMatchInlineSnapshot(` { x as FieldFormat} + formatFactory={x => x as fieldFormats.FieldFormat} /> ) ).toMatchInlineSnapshot(` diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js b/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js index c28276db37b2c..a6e6b18853bb8 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/__tests__/execute_job.js @@ -10,7 +10,7 @@ import sinon from 'sinon'; import nodeCrypto from '@elastic/node-crypto'; import { CancellationToken } from '../../../../common/cancellation_token'; -import { StringFormat, FieldFormatRegisty } from '../../../../../../../../src/plugins/data/server'; +import { fieldFormats } from '../../../../../../../../src/plugins/data/server'; import { executeJobFactory } from '../execute_job'; @@ -82,11 +82,11 @@ describe('CSV Execute Job', function() { _default_: { id: 'string', params: {} }, }; - const fieldFormatsService = new FieldFormatRegisty(); + const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); - fieldFormatsService.init(key => uiConfigMock[key], {}, [StringFormat]); + fieldFormatRegistry.init(key => uiConfigMock[key], {}, [fieldFormats.StringFormat]); - return fieldFormatsService; + return fieldFormatRegistry; }, plugins: { elasticsearch: { diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts index 016870ea11814..bbed348c2d90f 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts @@ -6,11 +6,7 @@ import expect from '@kbn/expect'; -import { - BytesFormat, - NumberFormat, - FieldFormatRegisty, -} from '../../../../../../../../src/plugins/data/server'; +import { fieldFormats } from '../../../../../../../../src/plugins/data/server'; import { fieldFormatMapFactory } from './field_format_map'; type ConfigValue = { number: { id: string; params: {} } } | string; @@ -36,9 +32,10 @@ describe('field format map', function() { const getConfig = (key: string) => configMock[key]; const testValue = '4000'; - const fieldFormats = new FieldFormatRegisty(); - fieldFormats.init(getConfig, {}, [BytesFormat, NumberFormat]); - const formatMap = fieldFormatMapFactory(indexPatternSavedObject, fieldFormats); + const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); + fieldFormatRegistry.init(getConfig, {}, [fieldFormats.BytesFormat, fieldFormats.NumberFormat]); + + const formatMap = fieldFormatMapFactory(indexPatternSavedObject, fieldFormatRegistry); it('should build field format map with entry per index pattern field', function() { expect(formatMap.has('field1')).to.be(true); diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts index 635a6e29a4e91..88fa355f2bc04 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts @@ -5,10 +5,7 @@ */ import _ from 'lodash'; -import { - FieldFormatRegisty, - IFieldFormatConfig, -} from '../../../../../../../../src/plugins/data/server'; +import { fieldFormats } from '../../../../../../../../src/plugins/data/server'; interface IndexPatternSavedObject { attributes: { @@ -28,7 +25,7 @@ interface IndexPatternSavedObject { */ export function fieldFormatMapFactory( indexPatternSavedObject: IndexPatternSavedObject, - fieldFormats: FieldFormatRegisty + fieldFormatRegistry: fieldFormats.FieldFormatRegistry ) { const formatsMap = new Map(); @@ -36,10 +33,13 @@ export function fieldFormatMapFactory( if (_.has(indexPatternSavedObject, 'attributes.fieldFormatMap')) { const fieldFormatMap = JSON.parse(indexPatternSavedObject.attributes.fieldFormatMap); Object.keys(fieldFormatMap).forEach(fieldName => { - const formatConfig: IFieldFormatConfig = fieldFormatMap[fieldName]; + const formatConfig: fieldFormats.IFieldFormatConfig = fieldFormatMap[fieldName]; if (!_.isEmpty(formatConfig)) { - formatsMap.set(fieldName, fieldFormats.getInstance(formatConfig.id, formatConfig.params)); + formatsMap.set( + fieldName, + fieldFormatRegistry.getInstance(formatConfig.id, formatConfig.params) + ); } }); } @@ -48,7 +48,7 @@ export function fieldFormatMapFactory( const indexFields = JSON.parse(_.get(indexPatternSavedObject, 'attributes.fields', '[]')); indexFields.forEach((field: any) => { if (!formatsMap.has(field.name)) { - formatsMap.set(field.name, fieldFormats.getDefaultInstance(field.type)); + formatsMap.set(field.name, fieldFormatRegistry.getDefaultInstance(field.type)); } }); From 0b1985ffc8230be4811864178a895212dcbed6dc Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Thu, 23 Jan 2020 15:29:21 +0300 Subject: [PATCH 05/13] fix CI --- .../export_types/csv/server/lib/field_format_map.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts index 24d5411a53563..f8ac592a019cc 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts @@ -29,7 +29,7 @@ describe('field format map', function() { number: { id: 'number', params: {} }, }; configMock['format:number:defaultPattern'] = '0,0.[000]'; - const getConfig = (key: string) => configMock[key] as fieldFormats.GetConfigFn; + const getConfig = ((key: string) => configMock[key]) as fieldFormats.GetConfigFn; const testValue = '4000'; const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); From 73ee1e6e5b55b23453fae147f7170865009aa05d Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Thu, 23 Jan 2020 15:33:08 +0300 Subject: [PATCH 06/13] getFieldFormatsRegistry -> getFieldFormatRegistry --- .../public/components/lib/tick_formatter.test.js | 4 ++-- .../ui/public/new_platform/new_platform.karma_mock.js | 6 +++--- .../data/public/field_formats/field_formats_service.ts | 10 +++++----- .../data/server/field_formats/field_formats_service.ts | 6 +++--- src/test_utils/public/stub_field_formats.ts | 2 +- src/test_utils/public/stub_index_pattern.js | 4 ++-- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/lib/tick_formatter.test.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/lib/tick_formatter.test.js index 76d3cff17343e..758ad1bc795f1 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/lib/tick_formatter.test.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/lib/tick_formatter.test.js @@ -19,7 +19,7 @@ import { npStart } from 'ui/new_platform'; import { createTickFormatter } from './tick_formatter'; -import { getFieldFormatsRegistry } from '../../../../../../test_utils/public/stub_field_formats'; +import { getFieldFormatRegistry } from '../../../../../../test_utils/public/stub_field_formats'; const mockUiSettings = { get: item => { @@ -47,7 +47,7 @@ const mockCore = { describe('createTickFormatter(format, template)', () => { npStart.plugins.data = { - fieldFormats: getFieldFormatsRegistry(mockCore), + fieldFormats: getFieldFormatRegistry(mockCore), }; test('returns a number with two decimal place by default', () => { diff --git a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js index dfd26bc4be039..daf5426e0f7d7 100644 --- a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js +++ b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js @@ -18,7 +18,7 @@ */ import sinon from 'sinon'; -import { getFieldFormatsRegistry } from '../../../../test_utils/public/stub_field_formats'; +import { getFieldFormatRegistry } from '../../../../test_utils/public/stub_field_formats'; import { METRIC_TYPE } from '@kbn/analytics'; const mockObservable = () => { @@ -102,7 +102,7 @@ export const npSetup = { getSavedQueryCount: sinon.fake(), }, }, - fieldFormats: getFieldFormatsRegistry(mockCore), + fieldFormats: getFieldFormatRegistry(mockCore), }, share: { register: () => {}, @@ -244,7 +244,7 @@ export const npStart = { }, }, }, - fieldFormats: getFieldFormatsRegistry(mockCore), + fieldFormats: getFieldFormatRegistry(mockCore), }, share: { toggleShareContextMenu: () => {}, diff --git a/src/plugins/data/public/field_formats/field_formats_service.ts b/src/plugins/data/public/field_formats/field_formats_service.ts index 081b1d50ca5eb..bd46bd078d024 100644 --- a/src/plugins/data/public/field_formats/field_formats_service.ts +++ b/src/plugins/data/public/field_formats/field_formats_service.ts @@ -21,16 +21,16 @@ import { CoreSetup } from 'src/core/public'; import { fieldFormats } from '../../common/field_formats'; export class FieldFormatsService { - private readonly fieldFormatsRegistry: fieldFormats.FieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); + private readonly fieldFormatRegistry: fieldFormats.FieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); public setup(core: CoreSetup) { core.uiSettings.getUpdate$().subscribe(({ key, newValue }) => { if (key === 'format:defaultTypeMap') { - this.fieldFormatsRegistry.parseDefaultTypeMap(newValue); + this.fieldFormatRegistry.parseDefaultTypeMap(newValue); } }); - this.fieldFormatsRegistry.init(core.uiSettings.get, { + this.fieldFormatRegistry.init(core.uiSettings.get, { parsedUrl: { origin: window.location.origin, pathname: window.location.pathname, @@ -38,11 +38,11 @@ export class FieldFormatsService { }, }); - return this.fieldFormatsRegistry as FieldFormatsSetup; + return this.fieldFormatRegistry as FieldFormatsSetup; } public start() { - return this.fieldFormatsRegistry as FieldFormatsStart; + return this.fieldFormatRegistry as FieldFormatsStart; } } diff --git a/src/plugins/data/server/field_formats/field_formats_service.ts b/src/plugins/data/server/field_formats/field_formats_service.ts index 05b7986e60dad..d3419eaac1bb3 100644 --- a/src/plugins/data/server/field_formats/field_formats_service.ts +++ b/src/plugins/data/server/field_formats/field_formats_service.ts @@ -34,7 +34,7 @@ export class FieldFormatsService { public start() { return { fieldFormatServiceFactory: async (uiSettings: IUiSettingsClient) => { - const fieldFormatsRegistry = new fieldFormats.FieldFormatRegistry(); + const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); const uiConfigs = await uiSettings.getAll(); const registeredUiSettings = uiSettings.getRegistered(); @@ -44,9 +44,9 @@ export class FieldFormatsService { } }); - fieldFormatsRegistry.init((key: string) => uiConfigs[key], {}, this.fieldFormatClasses); + fieldFormatRegistry.init((key: string) => uiConfigs[key], {}, this.fieldFormatClasses); - return fieldFormatsRegistry; + return fieldFormatRegistry; }, }; } diff --git a/src/test_utils/public/stub_field_formats.ts b/src/test_utils/public/stub_field_formats.ts index 42a2d36da112d..b11c1077f3a25 100644 --- a/src/test_utils/public/stub_field_formats.ts +++ b/src/test_utils/public/stub_field_formats.ts @@ -19,7 +19,7 @@ import { CoreSetup } from 'kibana/public'; import { fieldFormats } from '../../plugins/data/public'; -export const getFieldFormatsRegistry = (core: CoreSetup) => { +export const getFieldFormatRegistry = (core: CoreSetup) => { const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); fieldFormatRegistry.init(core.uiSettings.get, {}); diff --git a/src/test_utils/public/stub_index_pattern.js b/src/test_utils/public/stub_index_pattern.js index 9e1ad23602a01..3b362d79f99a7 100644 --- a/src/test_utils/public/stub_index_pattern.js +++ b/src/test_utils/public/stub_index_pattern.js @@ -33,10 +33,10 @@ setFieldFormats({ }), }); -import { getFieldFormatsRegistry } from './stub_field_formats'; +import { getFieldFormatRegistry } from './stub_field_formats'; export default function StubIndexPattern(pattern, getConfig, timeField, fields, core) { - const registeredFieldFormats = getFieldFormatsRegistry(core); + const registeredFieldFormats = getFieldFormatRegistry(core); this.id = pattern; this.title = pattern; From 380a92106335c80d2c77efee4e730cbe66bf5c13 Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Thu, 23 Jan 2020 16:27:04 +0300 Subject: [PATCH 07/13] fix CI --- src/legacy/ui/public/time_buckets/time_buckets.js | 6 +++--- .../data/common/field_formats/field_formats_registry.ts | 1 - .../data/public/field_formats/field_formats_service.ts | 4 +++- src/test_utils/public/stub_field_formats.ts | 3 ++- src/test_utils/public/stub_index_pattern.js | 4 ++-- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/legacy/ui/public/time_buckets/time_buckets.js b/src/legacy/ui/public/time_buckets/time_buckets.js index 96ba4bfb2ac2c..50a57d866099e 100644 --- a/src/legacy/ui/public/time_buckets/time_buckets.js +++ b/src/legacy/ui/public/time_buckets/time_buckets.js @@ -25,7 +25,7 @@ import { convertDurationToNormalizedEsInterval, convertIntervalToEsInterval, } from './calc_es_interval'; -import { FIELD_FORMAT_IDS, parseInterval } from '../../../../plugins/data/public'; +import { fieldFormats, parseInterval } from '../../../../plugins/data/public'; const getConfig = (...args) => npStart.core.uiSettings.get(...args); @@ -308,8 +308,8 @@ TimeBuckets.prototype.getScaledDateFormat = function() { }; TimeBuckets.prototype.getScaledDateFormatter = function() { - const fieldFormats = npStart.plugins.data.fieldFormats; - const DateFieldFormat = fieldFormats.getType(FIELD_FORMAT_IDS.DATE); + const fieldFormatsService = npStart.plugins.data.fieldFormats; + const DateFieldFormat = fieldFormatsService.getType(fieldFormats.FIELD_FORMAT_IDS.DATE); return new DateFieldFormat( { diff --git a/src/plugins/data/common/field_formats/field_formats_registry.ts b/src/plugins/data/common/field_formats/field_formats_registry.ts index 68707ce55b1f7..7bea3ba2b1e52 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.ts @@ -44,7 +44,6 @@ export class FieldFormatRegistry { defaultFieldConverters: IFieldFormatType[] = baseFormatters ) { const defaultTypeMap = getConfig('format:defaultTypeMap'); - this.register(defaultFieldConverters); this.parseDefaultTypeMap(defaultTypeMap); this.getConfig = getConfig; diff --git a/src/plugins/data/public/field_formats/field_formats_service.ts b/src/plugins/data/public/field_formats/field_formats_service.ts index bd46bd078d024..b59cbf323f76c 100644 --- a/src/plugins/data/public/field_formats/field_formats_service.ts +++ b/src/plugins/data/public/field_formats/field_formats_service.ts @@ -30,7 +30,9 @@ export class FieldFormatsService { } }); - this.fieldFormatRegistry.init(core.uiSettings.get, { + const getConfig = core.uiSettings.get.bind(core.uiSettings); + + this.fieldFormatRegistry.init(getConfig, { parsedUrl: { origin: window.location.origin, pathname: window.location.pathname, diff --git a/src/test_utils/public/stub_field_formats.ts b/src/test_utils/public/stub_field_formats.ts index b11c1077f3a25..a0af1b59a2ff4 100644 --- a/src/test_utils/public/stub_field_formats.ts +++ b/src/test_utils/public/stub_field_formats.ts @@ -21,8 +21,9 @@ import { fieldFormats } from '../../plugins/data/public'; export const getFieldFormatRegistry = (core: CoreSetup) => { const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); + const getConfig = core.uiSettings.get.bind(core.uiSettings); - fieldFormatRegistry.init(core.uiSettings.get, {}); + fieldFormatRegistry.init(getConfig, {}); return fieldFormatRegistry; }; diff --git a/src/test_utils/public/stub_index_pattern.js b/src/test_utils/public/stub_index_pattern.js index 3b362d79f99a7..0f90e677495d5 100644 --- a/src/test_utils/public/stub_index_pattern.js +++ b/src/test_utils/public/stub_index_pattern.js @@ -22,7 +22,7 @@ import sinon from 'sinon'; // because it is one of the few places that we need to access the IndexPattern class itself, rather // than just the type. Doing this as a temporary measure; it will be left behind when migrating to NP. -import { FieldList, fieldFormats, IndexPattern, indexPatterns } from '../../plugins/data/public'; +import { FieldList, IndexPattern, indexPatterns, KBN_FIELD_TYPES } from '../../plugins/data/public'; import { setFieldFormats } from '../../plugins/data/public/services'; @@ -56,7 +56,7 @@ export default function StubIndexPattern(pattern, getConfig, timeField, fields, this.flattenHit = indexPatterns.flattenHitWrapper(this, this.metaFields); this.formatHit = indexPatterns.formatHitProvider( this, - registeredFieldFormats.getDefaultInstance(fieldFormats.FIELD_FORMAT_IDS.STRING) + registeredFieldFormats.getDefaultInstance(KBN_FIELD_TYPES.STRING) ); this.fieldsFetcher = { apiClient: { baseUrl: '' } }; this.formatField = this.formatHit.formatField; From 223738ec9243b8ba3e71f18d1a1f7a8f2c8b6840 Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Thu, 23 Jan 2020 21:29:58 +0300 Subject: [PATCH 08/13] memoize - add resolve cache function --- .../data/common/field_formats/field_formats_registry.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/plugins/data/common/field_formats/field_formats_registry.ts b/src/plugins/data/common/field_formats/field_formats_registry.ts index 7bea3ba2b1e52..0252346e81448 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.ts @@ -154,7 +154,12 @@ export class FieldFormatRegistry { } return new ConcreteFieldFormat(params, this.getConfig); - } + }, + (formatId, params) => + JSON.stringify({ + formatId, + ...params, + }) ); /** From 1aa009765645bdbfb2afed9c2804bf25cb853a0a Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Thu, 23 Jan 2020 22:54:55 +0300 Subject: [PATCH 09/13] fix Jest --- .../field_editor/lib/__tests__/get_default_format.test.js | 8 ++++---- .../common/field_formats/field_formats_registry.test.ts | 2 +- .../__snapshots__/query_string_input.test.tsx.snap | 6 ------ 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/legacy/ui/public/field_editor/lib/__tests__/get_default_format.test.js b/src/legacy/ui/public/field_editor/lib/__tests__/get_default_format.test.js index e4084797c1b1e..96f574bf54ca6 100644 --- a/src/legacy/ui/public/field_editor/lib/__tests__/get_default_format.test.js +++ b/src/legacy/ui/public/field_editor/lib/__tests__/get_default_format.test.js @@ -18,7 +18,7 @@ */ import { getDefaultFormat } from '../get_default_format'; -import { NumberFormat } from '../../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../../plugins/data/public'; const getConfig = () => { return '0,0.[000]'; @@ -26,12 +26,12 @@ const getConfig = () => { describe('getDefaultFormat', () => { it('should create default format', () => { - const DefaultFormat = getDefaultFormat(NumberFormat); + const DefaultFormat = getDefaultFormat(fieldFormats.NumberFormat); const defaultFormatObject = new DefaultFormat(null, getConfig); - const formatObject = new NumberFormat(null, getConfig); + const formatObject = new fieldFormats.NumberFormat(null, getConfig); expect(DefaultFormat.id).toEqual(''); - expect(DefaultFormat.resolvedTitle).toEqual(NumberFormat.title); + expect(DefaultFormat.resolvedTitle).toEqual(fieldFormats.NumberFormat.title); expect(DefaultFormat.title).toEqual('- Default -'); expect(JSON.stringify(defaultFormatObject.params())).toEqual( JSON.stringify(formatObject.params()) diff --git a/src/plugins/data/common/field_formats/field_formats_registry.test.ts b/src/plugins/data/common/field_formats/field_formats_registry.test.ts index 7897558137a9d..40acdc7cd8037 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.test.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.test.ts @@ -26,7 +26,7 @@ const getValueOfPrivateField = (instance: any, field: string) => instance[field] describe('FieldFormatRegistry', () => { let fieldFormatRegistry: FieldFormatRegistry; let defaultMap = {}; - const getConfig = (() => {}) as GetConfigFn; + const getConfig = (() => defaultMap) as GetConfigFn; beforeEach(() => { fieldFormatRegistry = new FieldFormatRegistry(); diff --git a/src/plugins/data/public/ui/query_string_input/__snapshots__/query_string_input.test.tsx.snap b/src/plugins/data/public/ui/query_string_input/__snapshots__/query_string_input.test.tsx.snap index f38adff892099..2f2332bb06e3c 100644 --- a/src/plugins/data/public/ui/query_string_input/__snapshots__/query_string_input.test.tsx.snap +++ b/src/plugins/data/public/ui/query_string_input/__snapshots__/query_string_input.test.tsx.snap @@ -163,7 +163,6 @@ exports[`QueryStringInput Should disable autoFocus on EuiFieldText when disableA }, "fieldFormats": Object { "getByFieldType": [MockFunction], - "getConfig": [MockFunction], "getDefaultConfig": [MockFunction], "getDefaultInstance": [MockFunction], "getDefaultInstanceCacheResolver": [MockFunction], @@ -805,7 +804,6 @@ exports[`QueryStringInput Should disable autoFocus on EuiFieldText when disableA }, "fieldFormats": Object { "getByFieldType": [MockFunction], - "getConfig": [MockFunction], "getDefaultConfig": [MockFunction], "getDefaultInstance": [MockFunction], "getDefaultInstanceCacheResolver": [MockFunction], @@ -1429,7 +1427,6 @@ exports[`QueryStringInput Should pass the query language to the language switche }, "fieldFormats": Object { "getByFieldType": [MockFunction], - "getConfig": [MockFunction], "getDefaultConfig": [MockFunction], "getDefaultInstance": [MockFunction], "getDefaultInstanceCacheResolver": [MockFunction], @@ -2068,7 +2065,6 @@ exports[`QueryStringInput Should pass the query language to the language switche }, "fieldFormats": Object { "getByFieldType": [MockFunction], - "getConfig": [MockFunction], "getDefaultConfig": [MockFunction], "getDefaultInstance": [MockFunction], "getDefaultInstanceCacheResolver": [MockFunction], @@ -2692,7 +2688,6 @@ exports[`QueryStringInput Should render the given query 1`] = ` }, "fieldFormats": Object { "getByFieldType": [MockFunction], - "getConfig": [MockFunction], "getDefaultConfig": [MockFunction], "getDefaultInstance": [MockFunction], "getDefaultInstanceCacheResolver": [MockFunction], @@ -3331,7 +3326,6 @@ exports[`QueryStringInput Should render the given query 1`] = ` }, "fieldFormats": Object { "getByFieldType": [MockFunction], - "getConfig": [MockFunction], "getDefaultConfig": [MockFunction], "getDefaultInstance": [MockFunction], "getDefaultInstanceCacheResolver": [MockFunction], From 32388e4ade551a522ac5b1937073e8042c277d75 Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Fri, 24 Jan 2020 12:00:08 +0300 Subject: [PATCH 10/13] move IFieldFormatMetaParams to types.ts --- .../editors/color/color.js | 4 ++-- .../editors/color/color.test.js | 4 ++-- .../{ => constants}/base_formatters.ts | 4 ++-- .../common/field_formats/constants/index.ts | 20 ------------------- .../common/field_formats/converters/color.ts | 2 +- .../field_formats/converters/date_server.ts | 9 +++++++-- .../common/field_formats/converters/url.ts | 9 +++++++-- .../data/common/field_formats/field_format.ts | 10 +--------- .../field_formats/field_formats_registry.ts | 5 +++-- .../data/common/field_formats/static.ts | 7 ++++--- .../data/common/field_formats/types.ts | 9 +++++++++ .../export_types/csv/server/execute_job.ts | 1 - 12 files changed, 38 insertions(+), 46 deletions(-) rename src/plugins/data/common/field_formats/{ => constants}/base_formatters.ts (95%) delete mode 100644 src/plugins/data/common/field_formats/constants/index.ts diff --git a/src/legacy/ui/public/field_editor/components/field_format_editor/editors/color/color.js b/src/legacy/ui/public/field_editor/components/field_format_editor/editors/color/color.js index 231cc26553037..4ad04f08915e7 100644 --- a/src/legacy/ui/public/field_editor/components/field_format_editor/editors/color/color.js +++ b/src/legacy/ui/public/field_editor/components/field_format_editor/editors/color/color.js @@ -23,7 +23,7 @@ import { EuiBasicTable, EuiButton, EuiColorPicker, EuiFieldText, EuiSpacer } fro import { DefaultFormatEditor } from '../default'; -import { DEFAULT_CONVERTER_COLOR } from '../../../../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../../../../plugins/data/public'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -50,7 +50,7 @@ export class ColorFormatEditor extends DefaultFormatEditor { addColor = () => { const colors = [...this.props.formatParams.colors]; this.onChange({ - colors: [...colors, { ...DEFAULT_CONVERTER_COLOR }], + colors: [...colors, { ...fieldFormats.DEFAULT_CONVERTER_COLOR }], }); }; diff --git a/src/legacy/ui/public/field_editor/components/field_format_editor/editors/color/color.test.js b/src/legacy/ui/public/field_editor/components/field_format_editor/editors/color/color.test.js index 6618b624be1d0..486b1e34dcade 100644 --- a/src/legacy/ui/public/field_editor/components/field_format_editor/editors/color/color.test.js +++ b/src/legacy/ui/public/field_editor/components/field_format_editor/editors/color/color.test.js @@ -21,14 +21,14 @@ import React from 'react'; import { shallowWithI18nProvider } from 'test_utils/enzyme_helpers'; import { ColorFormatEditor } from './color'; -import { DEFAULT_CONVERTER_COLOR } from '../../../../../../../../plugins/data/public'; +import { fieldFormats } from '../../../../../../../../plugins/data/public'; const fieldType = 'string'; const format = { getConverterFor: jest.fn(), }; const formatParams = { - colors: [{ ...DEFAULT_CONVERTER_COLOR }], + colors: [{ ...fieldFormats.DEFAULT_CONVERTER_COLOR }], }; const onChange = jest.fn(); const onError = jest.fn(); diff --git a/src/plugins/data/common/field_formats/base_formatters.ts b/src/plugins/data/common/field_formats/constants/base_formatters.ts similarity index 95% rename from src/plugins/data/common/field_formats/base_formatters.ts rename to src/plugins/data/common/field_formats/constants/base_formatters.ts index 6b6e9fafbe64b..95aedd02d16d6 100644 --- a/src/plugins/data/common/field_formats/base_formatters.ts +++ b/src/plugins/data/common/field_formats/constants/base_formatters.ts @@ -17,7 +17,7 @@ * under the License. */ -import { IFieldFormatType } from './types'; +import { IFieldFormatType } from '../types'; import { BoolFormat, @@ -35,7 +35,7 @@ import { StringFormat, TruncateFormat, UrlFormat, -} from './converters'; +} from '../converters'; export const baseFormatters: IFieldFormatType[] = [ BoolFormat, diff --git a/src/plugins/data/common/field_formats/constants/index.ts b/src/plugins/data/common/field_formats/constants/index.ts deleted file mode 100644 index 7f95df4449631..0000000000000 --- a/src/plugins/data/common/field_formats/constants/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 { DEFAULT_CONVERTER_COLOR } from './color_default'; diff --git a/src/plugins/data/common/field_formats/converters/color.ts b/src/plugins/data/common/field_formats/converters/color.ts index ffc72ba9a2c30..20d9d6aee6d26 100644 --- a/src/plugins/data/common/field_formats/converters/color.ts +++ b/src/plugins/data/common/field_formats/converters/color.ts @@ -22,7 +22,7 @@ import { KBN_FIELD_TYPES } from '../../kbn_field_types/types'; import { FieldFormat } from '../field_format'; import { HtmlContextTypeConvert, FIELD_FORMAT_IDS } from '../types'; import { asPrettyString } from '../utils'; -import { DEFAULT_CONVERTER_COLOR } from '../constants'; +import { DEFAULT_CONVERTER_COLOR } from '../constants/color_default'; const convertTemplate = template('<%- val %>'); diff --git a/src/plugins/data/common/field_formats/converters/date_server.ts b/src/plugins/data/common/field_formats/converters/date_server.ts index acd8a027614af..cc7eba966cf0d 100644 --- a/src/plugins/data/common/field_formats/converters/date_server.ts +++ b/src/plugins/data/common/field_formats/converters/date_server.ts @@ -20,8 +20,13 @@ import { memoize, noop } from 'lodash'; import moment from 'moment-timezone'; import { KBN_FIELD_TYPES } from '../../kbn_field_types/types'; -import { FieldFormat, IFieldFormatMetaParams } from '../field_format'; -import { TextContextTypeConvert, FIELD_FORMAT_IDS, GetConfigFn } from '../types'; +import { FieldFormat } from '../field_format'; +import { + TextContextTypeConvert, + FIELD_FORMAT_IDS, + GetConfigFn, + IFieldFormatMetaParams, +} from '../types'; export class DateFormat extends FieldFormat { static id = FIELD_FORMAT_IDS.DATE; diff --git a/src/plugins/data/common/field_formats/converters/url.ts b/src/plugins/data/common/field_formats/converters/url.ts index 21688dd8d1138..7c3e1e1d2cad1 100644 --- a/src/plugins/data/common/field_formats/converters/url.ts +++ b/src/plugins/data/common/field_formats/converters/url.ts @@ -21,8 +21,13 @@ import { i18n } from '@kbn/i18n'; import { escape, memoize } from 'lodash'; import { getHighlightHtml } from '../utils'; import { KBN_FIELD_TYPES } from '../../kbn_field_types/types'; -import { FieldFormat, IFieldFormatMetaParams } from '../field_format'; -import { TextContextTypeConvert, HtmlContextTypeConvert, FIELD_FORMAT_IDS } from '../types'; +import { FieldFormat } from '../field_format'; +import { + TextContextTypeConvert, + HtmlContextTypeConvert, + IFieldFormatMetaParams, + FIELD_FORMAT_IDS, +} from '../types'; const templateMatchRE = /{{([\s\S]+?)}}/g; const whitelistUrlSchemes = ['http://', 'https://']; diff --git a/src/plugins/data/common/field_formats/field_format.ts b/src/plugins/data/common/field_formats/field_format.ts index c63dd4a6f558a..d605dcd2e78ac 100644 --- a/src/plugins/data/common/field_formats/field_format.ts +++ b/src/plugins/data/common/field_formats/field_format.ts @@ -27,6 +27,7 @@ import { FieldFormatConvertFunction, HtmlContextTypeOptions, TextContextTypeOptions, + IFieldFormatMetaParams, } from './types'; import { htmlContentTypeSetup, @@ -38,15 +39,6 @@ import { HtmlContextTypeConvert, TextContextTypeConvert } from './types'; const DEFAULT_CONTEXT_TYPE = TEXT_CONTEXT_TYPE; -export interface IFieldFormatMetaParams { - [key: string]: any; - parsedUrl?: { - origin: string; - pathname?: string; - basePath?: string; - }; -} - export abstract class FieldFormat { /** * @property {string} - Field Format Id diff --git a/src/plugins/data/common/field_formats/field_formats_registry.ts b/src/plugins/data/common/field_formats/field_formats_registry.ts index 811647b932fed..c4bd4289c995d 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.ts @@ -28,9 +28,10 @@ import { FIELD_FORMAT_IDS, IFieldFormatType, IFieldFormatId, + IFieldFormatMetaParams, } from './types'; -import { baseFormatters } from './base_formatters'; -import { FieldFormat, IFieldFormatMetaParams } from './field_format'; +import { baseFormatters } from './constants/base_formatters'; +import { FieldFormat } from './field_format'; export class FieldFormatRegistry { protected fieldFormats: Map = new Map(); diff --git a/src/plugins/data/common/field_formats/static.ts b/src/plugins/data/common/field_formats/static.ts index 2286366dc3f48..0981b94e00287 100644 --- a/src/plugins/data/common/field_formats/static.ts +++ b/src/plugins/data/common/field_formats/static.ts @@ -18,11 +18,12 @@ */ export { HTML_CONTEXT_TYPE, TEXT_CONTEXT_TYPE } from './content_types'; -export { FieldFormat, IFieldFormatMetaParams } from './field_format'; +export { FieldFormat } from './field_format'; export { FieldFormatRegistry } from './field_formats_registry'; export { getHighlightRequest, asPrettyString, getHighlightHtml } from './utils'; -export { baseFormatters } from './base_formatters'; + +export { baseFormatters } from './constants/base_formatters'; +export { DEFAULT_CONVERTER_COLOR } from './constants/color_default'; export * from './converters'; -export * from './constants'; export * from './types'; diff --git a/src/plugins/data/common/field_formats/types.ts b/src/plugins/data/common/field_formats/types.ts index 5c6e38aeaa43d..b6c10c9964f67 100644 --- a/src/plugins/data/common/field_formats/types.ts +++ b/src/plugins/data/common/field_formats/types.ts @@ -85,3 +85,12 @@ export type IFieldFormatType = (new (params?: any, getConfig?: GetConfigFn) => F id: IFieldFormatId; fieldType: string | string[]; }; + +export interface IFieldFormatMetaParams { + [key: string]: any; + parsedUrl?: { + origin: string; + pathname?: string; + basePath?: string; + }; +} diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts index 0eceda8cfbec6..fe64fdc96d904 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts @@ -5,7 +5,6 @@ */ import { i18n } from '@kbn/i18n'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths import { KibanaRequest } from '../../../../../../../src/core/server'; import { CSV_JOB_TYPE } from '../../../common/constants'; import { cryptoFactory } from '../../../server/lib'; From 369b1c09936ebc934746bc7a74c74157d6397216 Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Mon, 27 Jan 2020 11:22:36 +0300 Subject: [PATCH 11/13] FieldFormatRegistry -> FieldFormatsRegistry --- .../components/lib/tick_formatter.test.js | 4 +- .../new_platform/new_platform.karma_mock.js | 6 +- .../field_formats_registry.test.ts | 62 +++++++++---------- .../field_formats/field_formats_registry.ts | 2 +- .../data/common/field_formats/static.ts | 33 +++++++++- .../field_formats/field_formats_service.ts | 14 ++--- src/plugins/data/public/index.ts | 1 - .../index_patterns/index_pattern.test.ts | 2 +- src/plugins/data/public/mocks.ts | 2 +- .../field_formats/field_formats_service.ts | 6 +- src/test_utils/public/stub_field_formats.ts | 8 +-- src/test_utils/public/stub_index_pattern.js | 4 +- .../csv/server/execute_job.test.js | 6 +- .../csv/server/lib/field_format_map.test.ts | 6 +- .../csv/server/lib/field_format_map.ts | 6 +- 15 files changed, 94 insertions(+), 68 deletions(-) diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/lib/tick_formatter.test.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/lib/tick_formatter.test.js index 758ad1bc795f1..76d3cff17343e 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/lib/tick_formatter.test.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/lib/tick_formatter.test.js @@ -19,7 +19,7 @@ import { npStart } from 'ui/new_platform'; import { createTickFormatter } from './tick_formatter'; -import { getFieldFormatRegistry } from '../../../../../../test_utils/public/stub_field_formats'; +import { getFieldFormatsRegistry } from '../../../../../../test_utils/public/stub_field_formats'; const mockUiSettings = { get: item => { @@ -47,7 +47,7 @@ const mockCore = { describe('createTickFormatter(format, template)', () => { npStart.plugins.data = { - fieldFormats: getFieldFormatRegistry(mockCore), + fieldFormats: getFieldFormatsRegistry(mockCore), }; test('returns a number with two decimal place by default', () => { diff --git a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js index 176d6ee231762..6f4b20c425fc9 100644 --- a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js +++ b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js @@ -18,7 +18,7 @@ */ import sinon from 'sinon'; -import { getFieldFormatRegistry } from '../../../../test_utils/public/stub_field_formats'; +import { getFieldFormatsRegistry } from '../../../../test_utils/public/stub_field_formats'; import { METRIC_TYPE } from '@kbn/analytics'; const mockObservable = () => { @@ -108,7 +108,7 @@ export const npSetup = { msearch: sinon.fake(), }, }, - fieldFormats: getFieldFormatRegistry(mockCore), + fieldFormats: getFieldFormatsRegistry(mockCore), }, share: { register: () => {}, @@ -250,7 +250,7 @@ export const npStart = { }, }, }, - fieldFormats: getFieldFormatRegistry(mockCore), + fieldFormats: getFieldFormatsRegistry(mockCore), }, share: { toggleShareContextMenu: () => {}, diff --git a/src/plugins/data/common/field_formats/field_formats_registry.test.ts b/src/plugins/data/common/field_formats/field_formats_registry.test.ts index 40acdc7cd8037..5f6f9fdf897ff 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.test.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.test.ts @@ -16,21 +16,21 @@ * specific language governing permissions and limitations * under the License. */ -import { FieldFormatRegistry } from './field_formats_registry'; +import { FieldFormatsRegistry } from './field_formats_registry'; import { BoolFormat, PercentFormat, StringFormat } from './converters'; import { GetConfigFn, IFieldFormatType } from './types'; import { KBN_FIELD_TYPES } from '../../common'; const getValueOfPrivateField = (instance: any, field: string) => instance[field]; -describe('FieldFormatRegistry', () => { - let fieldFormatRegistry: FieldFormatRegistry; +describe('FieldFormatsRegistry', () => { + let fieldFormatsRegistry: FieldFormatsRegistry; let defaultMap = {}; const getConfig = (() => defaultMap) as GetConfigFn; beforeEach(() => { - fieldFormatRegistry = new FieldFormatRegistry(); - fieldFormatRegistry.init( + fieldFormatsRegistry = new FieldFormatsRegistry(); + fieldFormatsRegistry.init( getConfig, { parsedUrl: { @@ -43,17 +43,17 @@ describe('FieldFormatRegistry', () => { ); }); - test('should allows to create an instance of "FieldFormatRegistry"', () => { - expect(fieldFormatRegistry).toBeDefined(); + test('should allows to create an instance of "FieldFormatsRegistry"', () => { + expect(fieldFormatsRegistry).toBeDefined(); - expect(getValueOfPrivateField(fieldFormatRegistry, 'fieldFormats')).toBeDefined(); - expect(getValueOfPrivateField(fieldFormatRegistry, 'defaultMap')).toEqual({}); + expect(getValueOfPrivateField(fieldFormatsRegistry, 'fieldFormats')).toBeDefined(); + expect(getValueOfPrivateField(fieldFormatsRegistry, 'defaultMap')).toEqual({}); }); describe('init', () => { test('should provide an public "init" method', () => { - expect(fieldFormatRegistry.init).toBeDefined(); - expect(typeof fieldFormatRegistry.init).toBe('function'); + expect(fieldFormatsRegistry.init).toBeDefined(); + expect(typeof fieldFormatsRegistry.init).toBe('function'); }); test('should populate the "defaultMap" object', () => { @@ -61,22 +61,22 @@ describe('FieldFormatRegistry', () => { number: { id: 'number', params: {} }, }; - fieldFormatRegistry.init(getConfig, {}, []); - expect(getValueOfPrivateField(fieldFormatRegistry, 'defaultMap')).toEqual(defaultMap); + fieldFormatsRegistry.init(getConfig, {}, []); + expect(getValueOfPrivateField(fieldFormatsRegistry, 'defaultMap')).toEqual(defaultMap); }); }); describe('register', () => { test('should provide an public "register" method', () => { - expect(fieldFormatRegistry.register).toBeDefined(); - expect(typeof fieldFormatRegistry.register).toBe('function'); + expect(fieldFormatsRegistry.register).toBeDefined(); + expect(typeof fieldFormatsRegistry.register).toBe('function'); }); test('should register field formats', () => { - fieldFormatRegistry.register([StringFormat, BoolFormat]); + fieldFormatsRegistry.register([StringFormat, BoolFormat]); const registeredFieldFormatters: Map = getValueOfPrivateField( - fieldFormatRegistry, + fieldFormatsRegistry, 'fieldFormats' ); @@ -90,28 +90,28 @@ describe('FieldFormatRegistry', () => { describe('getType', () => { test('should provide an public "getType" method', () => { - expect(fieldFormatRegistry.getType).toBeDefined(); - expect(typeof fieldFormatRegistry.getType).toBe('function'); + expect(fieldFormatsRegistry.getType).toBeDefined(); + expect(typeof fieldFormatsRegistry.getType).toBe('function'); }); test('should return the registered type of the field format by identifier', () => { - fieldFormatRegistry.register([StringFormat]); + fieldFormatsRegistry.register([StringFormat]); - expect(fieldFormatRegistry.getType(StringFormat.id)).toBeDefined(); + expect(fieldFormatsRegistry.getType(StringFormat.id)).toBeDefined(); }); test('should return void if the field format type has not been registered', () => { - fieldFormatRegistry.register([BoolFormat]); + fieldFormatsRegistry.register([BoolFormat]); - expect(fieldFormatRegistry.getType(StringFormat.id)).toBeUndefined(); + expect(fieldFormatsRegistry.getType(StringFormat.id)).toBeUndefined(); }); }); describe('fieldFormatMetaParamsDecorator', () => { test('should set meta params for all instances of FieldFormats', () => { - fieldFormatRegistry.register([StringFormat]); + fieldFormatsRegistry.register([StringFormat]); - const DecoratedStingFormat = fieldFormatRegistry.getType(StringFormat.id); + const DecoratedStingFormat = fieldFormatsRegistry.getType(StringFormat.id); expect(DecoratedStingFormat).toBeDefined(); @@ -130,9 +130,9 @@ describe('FieldFormatRegistry', () => { }); test('should decorate static fields', () => { - fieldFormatRegistry.register([BoolFormat]); + fieldFormatsRegistry.register([BoolFormat]); - const DecoratedBoolFormat = fieldFormatRegistry.getType(BoolFormat.id); + const DecoratedBoolFormat = fieldFormatsRegistry.getType(BoolFormat.id); expect(DecoratedBoolFormat).toBeDefined(); @@ -145,14 +145,14 @@ describe('FieldFormatRegistry', () => { describe('getByFieldType', () => { test('should provide an public "getByFieldType" method', () => { - expect(fieldFormatRegistry.getByFieldType).toBeDefined(); - expect(typeof fieldFormatRegistry.getByFieldType).toBe('function'); + expect(fieldFormatsRegistry.getByFieldType).toBeDefined(); + expect(typeof fieldFormatsRegistry.getByFieldType).toBe('function'); }); test('should decorate returns types', () => { - fieldFormatRegistry.register([StringFormat, BoolFormat]); + fieldFormatsRegistry.register([StringFormat, BoolFormat]); - const [DecoratedStringFormat] = fieldFormatRegistry.getByFieldType(KBN_FIELD_TYPES.STRING); + const [DecoratedStringFormat] = fieldFormatsRegistry.getByFieldType(KBN_FIELD_TYPES.STRING); expect(DecoratedStringFormat).toBeDefined(); diff --git a/src/plugins/data/common/field_formats/field_formats_registry.ts b/src/plugins/data/common/field_formats/field_formats_registry.ts index c4bd4289c995d..9b85921b820c8 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.ts @@ -33,7 +33,7 @@ import { import { baseFormatters } from './constants/base_formatters'; import { FieldFormat } from './field_format'; -export class FieldFormatRegistry { +export class FieldFormatsRegistry { protected fieldFormats: Map = new Map(); protected defaultMap: Record = {}; protected metaParamsOptions: Record = {}; diff --git a/src/plugins/data/common/field_formats/static.ts b/src/plugins/data/common/field_formats/static.ts index 0981b94e00287..6d8691fa753e6 100644 --- a/src/plugins/data/common/field_formats/static.ts +++ b/src/plugins/data/common/field_formats/static.ts @@ -17,13 +17,40 @@ * under the License. */ +/** + * Everything the file exports is public + */ + export { HTML_CONTEXT_TYPE, TEXT_CONTEXT_TYPE } from './content_types'; export { FieldFormat } from './field_format'; -export { FieldFormatRegistry } from './field_formats_registry'; +export { FieldFormatsRegistry } from './field_formats_registry'; export { getHighlightRequest, asPrettyString, getHighlightHtml } from './utils'; export { baseFormatters } from './constants/base_formatters'; export { DEFAULT_CONVERTER_COLOR } from './constants/color_default'; -export * from './converters'; -export * from './types'; +export { + BoolFormat, + BytesFormat, + ColorFormat, + DateFormat, + DateNanosFormat, + DurationFormat, + IpFormat, + NumberFormat, + PercentFormat, + RelativeDateFormat, + SourceFormat, + StaticLookupFormat, + StringFormat, + TruncateFormat, +} from './converters'; + +export { + FIELD_FORMAT_IDS, + ContentType, + IFieldFormatConfig, + IFieldFormatType, + IFieldFormat, + IFieldFormatId, +} from './types'; diff --git a/src/plugins/data/public/field_formats/field_formats_service.ts b/src/plugins/data/public/field_formats/field_formats_service.ts index b59cbf323f76c..68df0aa254580 100644 --- a/src/plugins/data/public/field_formats/field_formats_service.ts +++ b/src/plugins/data/public/field_formats/field_formats_service.ts @@ -21,18 +21,18 @@ import { CoreSetup } from 'src/core/public'; import { fieldFormats } from '../../common/field_formats'; export class FieldFormatsService { - private readonly fieldFormatRegistry: fieldFormats.FieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); + private readonly fieldFormatsRegistry: fieldFormats.FieldFormatsRegistry = new fieldFormats.FieldFormatsRegistry(); public setup(core: CoreSetup) { core.uiSettings.getUpdate$().subscribe(({ key, newValue }) => { if (key === 'format:defaultTypeMap') { - this.fieldFormatRegistry.parseDefaultTypeMap(newValue); + this.fieldFormatsRegistry.parseDefaultTypeMap(newValue); } }); const getConfig = core.uiSettings.get.bind(core.uiSettings); - this.fieldFormatRegistry.init(getConfig, { + this.fieldFormatsRegistry.init(getConfig, { parsedUrl: { origin: window.location.origin, pathname: window.location.pathname, @@ -40,16 +40,16 @@ export class FieldFormatsService { }, }); - return this.fieldFormatRegistry as FieldFormatsSetup; + return this.fieldFormatsRegistry as FieldFormatsSetup; } public start() { - return this.fieldFormatRegistry as FieldFormatsStart; + return this.fieldFormatsRegistry as FieldFormatsStart; } } /** @public */ -export type FieldFormatsSetup = Pick; +export type FieldFormatsSetup = Pick; /** @public */ -export type FieldFormatsStart = Omit; +export type FieldFormatsStart = Omit; diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index ddf398c830376..85b3e00d4d95b 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -56,7 +56,6 @@ export { esKuery, esQuery, fieldFormats, - // field formats // index patterns isFilterable, // kbn field types diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts index 650d2d3a425b1..059df6d4eb0f8 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts @@ -125,7 +125,7 @@ describe('IndexPattern', () => { setNotifications(notifications); setFieldFormats(({ getDefaultInstance: jest.fn(), - } as unknown) as fieldFormats.FieldFormatRegistry); + } as unknown) as fieldFormats.FieldFormatsRegistry); return create(indexPatternId).then((pattern: IndexPattern) => { indexPattern = pattern; diff --git a/src/plugins/data/public/mocks.ts b/src/plugins/data/public/mocks.ts index 2126dcffe3383..847d79fdc87d1 100644 --- a/src/plugins/data/public/mocks.ts +++ b/src/plugins/data/public/mocks.ts @@ -35,7 +35,7 @@ const autocompleteMock: any = { hasQuerySuggestions: jest.fn(), }; -const fieldFormatsMock: PublicMethodsOf = { +const fieldFormatsMock: PublicMethodsOf = { getByFieldType: jest.fn(), getDefaultConfig: jest.fn(), getDefaultInstance: jest.fn() as any, diff --git a/src/plugins/data/server/field_formats/field_formats_service.ts b/src/plugins/data/server/field_formats/field_formats_service.ts index d3419eaac1bb3..923904db9def0 100644 --- a/src/plugins/data/server/field_formats/field_formats_service.ts +++ b/src/plugins/data/server/field_formats/field_formats_service.ts @@ -34,7 +34,7 @@ export class FieldFormatsService { public start() { return { fieldFormatServiceFactory: async (uiSettings: IUiSettingsClient) => { - const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); + const fieldFormatsRegistry = new fieldFormats.FieldFormatsRegistry(); const uiConfigs = await uiSettings.getAll(); const registeredUiSettings = uiSettings.getRegistered(); @@ -44,9 +44,9 @@ export class FieldFormatsService { } }); - fieldFormatRegistry.init((key: string) => uiConfigs[key], {}, this.fieldFormatClasses); + fieldFormatsRegistry.init((key: string) => uiConfigs[key], {}, this.fieldFormatClasses); - return fieldFormatRegistry; + return fieldFormatsRegistry; }, }; } diff --git a/src/test_utils/public/stub_field_formats.ts b/src/test_utils/public/stub_field_formats.ts index a0af1b59a2ff4..32bdca1eea258 100644 --- a/src/test_utils/public/stub_field_formats.ts +++ b/src/test_utils/public/stub_field_formats.ts @@ -19,11 +19,11 @@ import { CoreSetup } from 'kibana/public'; import { fieldFormats } from '../../plugins/data/public'; -export const getFieldFormatRegistry = (core: CoreSetup) => { - const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); +export const getFieldFormatsRegistry = (core: CoreSetup) => { + const fieldFormatsRegistry = new fieldFormats.FieldFormatsRegistry(); const getConfig = core.uiSettings.get.bind(core.uiSettings); - fieldFormatRegistry.init(getConfig, {}); + fieldFormatsRegistry.init(getConfig, {}); - return fieldFormatRegistry; + return fieldFormatsRegistry; }; diff --git a/src/test_utils/public/stub_index_pattern.js b/src/test_utils/public/stub_index_pattern.js index 0f90e677495d5..4369661e9e197 100644 --- a/src/test_utils/public/stub_index_pattern.js +++ b/src/test_utils/public/stub_index_pattern.js @@ -33,10 +33,10 @@ setFieldFormats({ }), }); -import { getFieldFormatRegistry } from './stub_field_formats'; +import { getFieldFormatsRegistry } from './stub_field_formats'; export default function StubIndexPattern(pattern, getConfig, timeField, fields, core) { - const registeredFieldFormats = getFieldFormatRegistry(core); + const registeredFieldFormats = getFieldFormatsRegistry(core); this.id = pattern; this.title = pattern; diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.test.js b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.test.js index bf8240494ad26..1abc923d340e6 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.test.js +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.test.js @@ -75,11 +75,11 @@ describe('CSV Execute Job', function() { _default_: { id: 'string', params: {} }, }; - const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); + const fieldFormatsRegistry = new fieldFormats.FieldFormatsRegistry(); - fieldFormatRegistry.init(key => uiConfigMock[key], {}, [fieldFormats.StringFormat]); + fieldFormatsRegistry.init(key => uiConfigMock[key], {}, [fieldFormats.StringFormat]); - return fieldFormatRegistry; + return fieldFormatsRegistry; }, plugins: { elasticsearch: { diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts index f8ac592a019cc..d1fa44773972f 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts @@ -32,10 +32,10 @@ describe('field format map', function() { const getConfig = ((key: string) => configMock[key]) as fieldFormats.GetConfigFn; const testValue = '4000'; - const fieldFormatRegistry = new fieldFormats.FieldFormatRegistry(); - fieldFormatRegistry.init(getConfig, {}, [fieldFormats.BytesFormat, fieldFormats.NumberFormat]); + const fieldFormatsRegistry = new fieldFormats.FieldFormatsRegistry(); + fieldFormatsRegistry.init(getConfig, {}, [fieldFormats.BytesFormat, fieldFormats.NumberFormat]); - const formatMap = fieldFormatMapFactory(indexPatternSavedObject, fieldFormatRegistry); + const formatMap = fieldFormatMapFactory(indexPatternSavedObject, fieldFormatsRegistry); it('should build field format map with entry per index pattern field', function() { expect(formatMap.has('field1')).to.be(true); diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts index 88fa355f2bc04..dba97b508f93e 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts @@ -25,7 +25,7 @@ interface IndexPatternSavedObject { */ export function fieldFormatMapFactory( indexPatternSavedObject: IndexPatternSavedObject, - fieldFormatRegistry: fieldFormats.FieldFormatRegistry + fieldFormatsRegistry: fieldFormats.FieldFormatsRegistry ) { const formatsMap = new Map(); @@ -38,7 +38,7 @@ export function fieldFormatMapFactory( if (!_.isEmpty(formatConfig)) { formatsMap.set( fieldName, - fieldFormatRegistry.getInstance(formatConfig.id, formatConfig.params) + fieldFormatsRegistry.getInstance(formatConfig.id, formatConfig.params) ); } }); @@ -48,7 +48,7 @@ export function fieldFormatMapFactory( const indexFields = JSON.parse(_.get(indexPatternSavedObject, 'attributes.fields', '[]')); indexFields.forEach((field: any) => { if (!formatsMap.has(field.name)) { - formatsMap.set(field.name, fieldFormatRegistry.getDefaultInstance(field.type)); + formatsMap.set(field.name, fieldFormatsRegistry.getDefaultInstance(field.type)); } }); From 91e6d123e65903ebbdc7600b0363add59dc82fcb Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Mon, 27 Jan 2020 11:44:14 +0300 Subject: [PATCH 12/13] update src/core/MIGRATION.md --- src/core/MIGRATION.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/MIGRATION.md b/src/core/MIGRATION.md index 087888922ac9b..f8699364fa9e2 100644 --- a/src/core/MIGRATION.md +++ b/src/core/MIGRATION.md @@ -1231,8 +1231,8 @@ This table shows where these uiExports have moved to in the New Platform. In mos | `docViews` | | | | `embeddableActions` | | Should be an API on the embeddables plugin. | | `embeddableFactories` | | Should be an API on the embeddables plugin. | -| `fieldFormatEditors` | | | -| `fieldFormats` | | | +| `fieldFormatEditors` | | | +| `fieldFormats` | [`plugins.data.fieldFormats`](./src/plugins/data/public/field_formats) | | | `hacks` | n/a | Just run the code in your plugin's `start` method. | | `home` | [`plugins.home.featureCatalogue.register`](./src/plugins/home/public/feature_catalogue) | Must add `home` as a dependency in your kibana.json. | | `indexManagement` | | Should be an API on the indexManagement plugin. | From 74d57356d6278f81afa1b13dd3fd16c0af5cc27c Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Mon, 27 Jan 2020 12:36:00 +0300 Subject: [PATCH 13/13] update public contract --- src/plugins/data/common/field_formats/static.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/plugins/data/common/field_formats/static.ts b/src/plugins/data/common/field_formats/static.ts index 6d8691fa753e6..186a0ff6ede5c 100644 --- a/src/plugins/data/common/field_formats/static.ts +++ b/src/plugins/data/common/field_formats/static.ts @@ -42,11 +42,13 @@ export { RelativeDateFormat, SourceFormat, StaticLookupFormat, + UrlFormat, StringFormat, TruncateFormat, } from './converters'; export { + GetConfigFn, FIELD_FORMAT_IDS, ContentType, IFieldFormatConfig,