Skip to content

Commit

Permalink
[FieldFormats] Reduce any usage (#111530) (#111965)
Browse files Browse the repository at this point in the history
Co-authored-by: Anton Dosov <[email protected]>
  • Loading branch information
kibanamachine and Dosant authored Sep 13, 2021
1 parent 723395c commit e3b8f04
Show file tree
Hide file tree
Showing 50 changed files with 310 additions and 217 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,14 @@ describe('Field', function () {
it('spec snapshot', () => {
const field = new IndexPatternField(fieldValues);
const getFormatterForField = () =>
({
(({
toJSON: () => ({
id: 'number',
params: {
pattern: '$0,0.[00]',
},
}),
} as FieldFormat);
} as unknown) as FieldFormat);
expect(field.toSpec({ getFormatterForField })).toMatchSnapshot();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -289,17 +289,17 @@ describe('IndexPattern', () => {

describe('toSpec', () => {
test('should match snapshot', () => {
const formatter = {
const formatter = ({
toJSON: () => ({ id: 'number', params: { pattern: '$0,0.[00]' } }),
} as FieldFormat;
} as unknown) as FieldFormat;
indexPattern.getFormatterForField = () => formatter;
expect(indexPattern.toSpec()).toMatchSnapshot();
});

test('can restore from spec', async () => {
const formatter = {
const formatter = ({
toJSON: () => ({ id: 'number', params: { pattern: '$0,0.[00]' } }),
} as FieldFormat;
} as unknown) as FieldFormat;
indexPattern.getFormatterForField = () => formatter;
const spec = indexPattern.toSpec();
const restoredPattern = new IndexPattern({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,7 @@ export class SearchSource {
body.query = buildEsQuery(index, query, filters, esQueryConfigs);

if (highlightAll && body.query) {
body.highlight = getHighlightRequest(body.query, getConfig(UI_SETTINGS.DOC_HIGHLIGHT));
body.highlight = getHighlightRequest(getConfig(UI_SETTINGS.DOC_HIGHLIGHT));
delete searchRequest.highlightAll;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export const formatTopLevelObject = (
const displayKey = fields.getByName ? fields.getByName(key)?.displayName : undefined;
const formatter = field
? indexPattern.getFormatterForField(field)
: { convert: (v: string, ...rest: unknown[]) => String(v) };
: { convert: (v: unknown, ...rest: unknown[]) => String(v) };
if (!values.map) return;
const formatted = values
.map((val: unknown) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export const getRenderCellValueFn = (
: undefined;
const formatter = subField
? indexPattern.getFormatterForField(subField)
: { convert: (v: string, ...rest: unknown[]) => String(v) };
: { convert: (v: unknown, ...rest: unknown[]) => String(v) };
const formatted = (values as unknown[])
.map((val: unknown) =>
formatter.convert(val, 'html', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const setup = (
return convert.call(format, value, options);
}

const subValues = value.map((v: any) => recurse(v, options));
const subValues = value.map((v: unknown) => recurse(v, options));
const useMultiLine = subValues.some((sub: string) => sub.indexOf('\n') > -1);

return subValues.join(',' + (useMultiLine ? '\n' : ' '));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import { BoolFormat } from './boolean';

describe('Boolean Format', () => {
let boolean: Record<string, any>;
let boolean: BoolFormat;

beforeEach(() => {
boolean = new BoolFormat({}, jest.fn());
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/field_formats/common/converters/boolean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class BoolFormat extends FieldFormat {
});
static fieldType = [KBN_FIELD_TYPES.BOOLEAN, KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.STRING];

textConvert: TextContextTypeConvert = (value) => {
textConvert: TextContextTypeConvert = (value: string | number | boolean) => {
if (typeof value === 'string') {
value = value.trim().toLowerCase();
}
Expand Down
9 changes: 5 additions & 4 deletions src/plugins/field_formats/common/converters/bytes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@

import { BytesFormat } from './bytes';
import { FORMATS_UI_SETTINGS } from '../constants/ui_settings';
import { FieldFormatsGetConfigFn } from '../types';

describe('BytesFormat', () => {
const config: Record<string, any> = {};
const config: { [key: string]: string } = {
[FORMATS_UI_SETTINGS.FORMAT_BYTES_DEFAULT_PATTERN]: '0,0.[000]b',
};

config[FORMATS_UI_SETTINGS.FORMAT_BYTES_DEFAULT_PATTERN] = '0,0.[000]b';

const getConfig = (key: string) => config[key];
const getConfig: FieldFormatsGetConfigFn = (key: string) => config[key];

test('default pattern', () => {
const formatter = new BytesFormat({}, getConfig);
Expand Down
6 changes: 3 additions & 3 deletions src/plugins/field_formats/common/converters/color.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ export class ColorFormat extends FieldFormat {
};
}

findColorRuleForVal(val: any) {
findColorRuleForVal(val: string | number) {
switch (this.param('fieldType')) {
case 'string':
return findLast(this.param('colors'), (colorParam: typeof DEFAULT_CONVERTER_COLOR) => {
return new RegExp(colorParam.regex).test(val);
return new RegExp(colorParam.regex).test(val as string);
});

case 'number':
Expand All @@ -50,7 +50,7 @@ export class ColorFormat extends FieldFormat {
}
}

htmlConvert: HtmlContextTypeConvert = (val) => {
htmlConvert: HtmlContextTypeConvert = (val: string | number) => {
const color = this.findColorRuleForVal(val) as typeof DEFAULT_CONVERTER_COLOR;

const displayVal = escape(asPrettyString(val));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,23 @@

import moment from 'moment-timezone';
import { DateNanosFormat, analysePatternForFract, formatWithNanos } from './date_nanos_shared';
import { FieldFormatsGetConfigFn } from '../types';

describe('Date Nanos Format', () => {
let convert: Function;
let mockConfig: Record<string, any>;
let mockConfig: {
dateNanosFormat: string;
'dateFormat:tz': string;
[other: string]: string;
};

beforeEach(() => {
mockConfig = {};
mockConfig.dateNanosFormat = 'MMMM Do YYYY, HH:mm:ss.SSSSSSSSS';
mockConfig['dateFormat:tz'] = 'Browser';
mockConfig = {
dateNanosFormat: 'MMMM Do YYYY, HH:mm:ss.SSSSSSSSS',
'dateFormat:tz': 'Browser',
};

const getConfig = (key: string) => mockConfig[key];
const getConfig: FieldFormatsGetConfigFn = (key: string) => mockConfig[key];
const date = new DateNanosFormat({}, getConfig);

convert = date.convert.bind(date);
Expand Down
21 changes: 14 additions & 7 deletions src/plugins/field_formats/common/converters/date_nanos_shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,27 @@ import moment, { Moment } from 'moment';
import { FieldFormat, FIELD_FORMAT_IDS } from '../';
import { TextContextTypeConvert } from '../types';

interface FractPatternObject {
length: number;
patternNanos: string;
pattern: string;
patternEscaped: string;
}

/**
* Analyse the given moment.js format pattern for the fractional sec part (S,SS,SSS...)
* returning length, match, pattern and an escaped pattern, that excludes the fractional
* part when formatting with moment.js -> e.g. [SSS]
*/
export function analysePatternForFract(pattern: string) {
const fracSecMatch = pattern.match('S+') as any; // extract fractional seconds sub-pattern
export function analysePatternForFract(pattern: string): FractPatternObject {
const fracSecMatch = pattern.match('S+'); // extract fractional seconds sub-pattern
const fracSecMatchStr = fracSecMatch ? fracSecMatch[0] : '';

return {
length: fracSecMatchStr.length,
patternNanos: fracSecMatchStr,
pattern,
patternEscaped: fracSecMatchStr ? pattern.replace(fracSecMatch, `[${fracSecMatch}]`) : '',
patternEscaped: fracSecMatchStr ? pattern.replace(fracSecMatchStr, `[${fracSecMatchStr}]`) : '',
};
}

Expand All @@ -38,7 +45,7 @@ export function analysePatternForFract(pattern: string) {
export function formatWithNanos(
dateMomentObj: Moment,
valRaw: string,
fracPatternObj: Record<string, any>
fracPatternObj: FractPatternObject
) {
if (fracPatternObj.length <= 3) {
// S,SS,SSS is formatted correctly by moment.js
Expand Down Expand Up @@ -77,7 +84,7 @@ export class DateNanosFormat extends FieldFormat {
};
}

textConvert: TextContextTypeConvert = (val) => {
textConvert: TextContextTypeConvert = (val: string | number) => {
// don't give away our ref to converter so
// we can hot-swap when config changes
const pattern = this.param('pattern');
Expand All @@ -91,7 +98,7 @@ export class DateNanosFormat extends FieldFormat {
this.timeZone = timezone;
this.memoizedPattern = pattern;

this.memoizedConverter = memoize(function converter(value: any) {
this.memoizedConverter = memoize(function converter(value: string | number) {
if (value === null || value === undefined) {
return '-';
}
Expand All @@ -102,7 +109,7 @@ export class DateNanosFormat extends FieldFormat {
// fallback for max/min aggregation, where unixtime in ms is returned as a number
// aggregations in Elasticsearch generally just return ms
return date.format(fallbackPattern);
} else if (date.isValid()) {
} else if (date.isValid() && typeof value === 'string') {
return formatWithNanos(date, value, fractPattern);
} else {
return value;
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/field_formats/common/converters/duration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,9 +315,9 @@ describe('Duration Format', () => {
showSuffix: boolean | undefined;
useShortSuffix?: boolean;
includeSpaceWithSuffix?: boolean;
fixtures: any[];
fixtures: Array<{ input: number; output: string }>;
}) {
fixtures.forEach((fixture: Record<string, any>) => {
fixtures.forEach((fixture: { input: number; output: string }) => {
const input = fixture.input;
const output = fixture.output;

Expand Down
2 changes: 1 addition & 1 deletion src/plugins/field_formats/common/converters/duration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ export class DurationFormat extends FieldFormat {
};
}

textConvert: TextContextTypeConvert = (val) => {
textConvert: TextContextTypeConvert = (val: number) => {
const inputFormat = this.param('inputFormat');
const outputFormat = this.param('outputFormat') as keyof Duration;
const outputPrecision = this.param('outputPrecision');
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/field_formats/common/converters/histogram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class HistogramFormat extends FieldFormat {
};
}

textConvert: TextContextTypeConvert = (val) => {
textConvert: TextContextTypeConvert = (val: number) => {
if (typeof val === 'number') {
const subFormatId = this.param('id');
const SubFormat =
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/field_formats/common/converters/ip.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import { IpFormat } from './ip';

describe('IP Address Format', () => {
let ip: Record<string, any>;
let ip: IpFormat;

beforeEach(() => {
ip = new IpFormat({}, jest.fn());
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/field_formats/common/converters/ip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ export class IpFormat extends FieldFormat {
});
static fieldType = KBN_FIELD_TYPES.IP;

textConvert: TextContextTypeConvert = (val) => {
textConvert: TextContextTypeConvert = (val: number) => {
if (val === undefined || val === null) return '-';
if (!isFinite(val)) return val;
if (!isFinite(val)) return String(val);

// shazzam!
// eslint-disable-next-line no-bitwise
Expand Down
6 changes: 3 additions & 3 deletions src/plugins/field_formats/common/converters/number.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import { NumberFormat } from './number';
import { FORMATS_UI_SETTINGS } from '../constants/ui_settings';

describe('NumberFormat', () => {
const config: Record<string, any> = {};

config[FORMATS_UI_SETTINGS.FORMAT_NUMBER_DEFAULT_PATTERN] = '0,0.[000]';
const config: { [key: string]: string } = {
[FORMATS_UI_SETTINGS.FORMAT_NUMBER_DEFAULT_PATTERN]: '0,0.[000]',
};

const getConfig = (key: string) => config[key];

Expand Down
4 changes: 2 additions & 2 deletions src/plugins/field_formats/common/converters/numeral.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { FORMATS_UI_SETTINGS } from '../constants/ui_settings';

const numeralInst = numeral();

numeralLanguages.forEach((numeralLanguage: Record<string, any>) => {
numeralLanguages.forEach((numeralLanguage: Record<string, { id: string; lang: string }>) => {
numeral.language(numeralLanguage.id, numeralLanguage.lang);
});

Expand All @@ -31,7 +31,7 @@ export abstract class NumeralFormat extends FieldFormat {
pattern: this.getConfig!(`format:${this.id}:defaultPattern`),
});

protected getConvertedValue(val: any): string {
protected getConvertedValue(val: number | string): string {
if (val === -Infinity) return '-∞';
if (val === +Infinity) return '+∞';
if (typeof val !== 'number') {
Expand Down
6 changes: 3 additions & 3 deletions src/plugins/field_formats/common/converters/percent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import { PercentFormat } from './percent';
import { FORMATS_UI_SETTINGS } from '../constants/ui_settings';

describe('PercentFormat', () => {
const config: Record<string, any> = {};

config[FORMATS_UI_SETTINGS.FORMAT_PERCENT_DEFAULT_PATTERN] = '0,0.[000]%';
const config: { [key: string]: string } = {
[FORMATS_UI_SETTINGS.FORMAT_PERCENT_DEFAULT_PATTERN]: '0,0.[000]%',
};

const getConfig = (key: string) => config[key];

Expand Down
2 changes: 1 addition & 1 deletion src/plugins/field_formats/common/converters/percent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class PercentFormat extends NumeralFormat {
fractional: true,
});

textConvert: TextContextTypeConvert = (val) => {
textConvert: TextContextTypeConvert = (val: string | number) => {
const formatted = super.getConvertedValue(val);

if (this.param('fractional')) {
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/field_formats/common/converters/relative_date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class RelativeDateFormat extends FieldFormat {
});
static fieldType = KBN_FIELD_TYPES.DATE;

textConvert: TextContextTypeConvert = (val) => {
textConvert: TextContextTypeConvert = (val: string | number) => {
if (val === null || val === undefined) {
return '-';
}
Expand All @@ -29,7 +29,7 @@ export class RelativeDateFormat extends FieldFormat {
if (date.isValid()) {
return date.fromNow();
} else {
return val;
return String(val);
}
};
}
16 changes: 8 additions & 8 deletions src/plugins/field_formats/common/converters/source.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ export class SourceFormat extends FieldFormat {
static title = '_source';
static fieldType = KBN_FIELD_TYPES._SOURCE;

textConvert: TextContextTypeConvert = (value) => JSON.stringify(value);
textConvert: TextContextTypeConvert = (value: string) => JSON.stringify(value);

htmlConvert: HtmlContextTypeConvert = (value, options = {}) => {
htmlConvert: HtmlContextTypeConvert = (value: string, options = {}) => {
const { field, hit, indexPattern } = options;

if (!field) {
Expand All @@ -52,18 +52,18 @@ export class SourceFormat extends FieldFormat {
return escape(converter(value));
}

const highlights = (hit && hit.highlight) || {};
const highlights: Record<string, string[]> = (hit && hit.highlight) || {};
// TODO: remove index pattern dependency
const formatted = indexPattern.formatHit(hit);
const highlightPairs: any[] = [];
const sourcePairs: any[] = [];
const formatted = hit ? indexPattern!.formatHit(hit) : {};
const highlightPairs: Array<[string, string]> = [];
const sourcePairs: Array<[string, string]> = [];
const isShortDots = this.getConfig!(FORMATS_UI_SETTINGS.SHORT_DOTS_ENABLE);

keys(formatted).forEach((key) => {
const pairs = highlights[key] ? highlightPairs : sourcePairs;
const newField = isShortDots ? shortenDottedString(key) : key;
const val = formatted[key];
pairs.push([newField, val]);
const val = formatted![key];
pairs.push([newField as string, val]);
}, []);

return ReactDOM.renderToStaticMarkup(
Expand Down
Loading

0 comments on commit e3b8f04

Please sign in to comment.