Skip to content

Commit

Permalink
[TSVB] [Table] js -> ts conversion (#105094)
Browse files Browse the repository at this point in the history
* table js -> ts

* remove any's

* fix CI

Co-authored-by: Kibana Machine <[email protected]>
  • Loading branch information
alexwizp and kibanamachine authored Jul 27, 2021
1 parent a6211f8 commit fcaa4aa
Show file tree
Hide file tree
Showing 66 changed files with 1,187 additions and 985 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import { getLastValue, isEmptyValue, EMPTY_VALUE } from './last_value_utils';
import { clone } from 'lodash';
import { PanelDataArray } from './types/vis_data';

describe('getLastValue(data)', () => {
test('should return data, if data is not an array', () => {
Expand Down Expand Up @@ -40,7 +41,7 @@ describe('getLastValue(data)', () => {
getLastValue([
[1, null],
[2, undefined],
])
] as PanelDataArray[])
).toBe(EMPTY_VALUE);
});
});
Expand Down
7 changes: 4 additions & 3 deletions src/plugins/vis_type_timeseries/common/last_value_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@
*/

import { isArray, last, isEqual } from 'lodash';
import type { PanelDataArray } from './types/vis_data';

export const EMPTY_VALUE = null;
export const DISPLAY_EMPTY_VALUE = '-';

const extractValue = (data: unknown[] | void) => (data && data[1]) ?? EMPTY_VALUE;
const extractValue = (data: PanelDataArray) => (data && data[1]) ?? EMPTY_VALUE;

export const getLastValue = (data: unknown) => {
export const getLastValue = (data: PanelDataArray[] | string | number) => {
if (!isArray(data)) {
return data;
}

return extractValue(last(data));
return extractValue(last(data)!);
};

export const isEmptyValue = (value: unknown) => isEqual(value, EMPTY_VALUE);
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@

const percentileNumberTest = /\d+\.\d+/;

export const toPercentileNumber = (value: string) =>
export const toPercentileNumber = (value: number | string) =>
percentileNumberTest.test(`${value}`) ? value : `${value}.0`;
4 changes: 3 additions & 1 deletion src/plugins/vis_type_timeseries/common/types/vis_data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,15 @@ export interface PanelSeries {
export interface PanelData {
id: string;
label: string;
data: Array<[number, number]>;
data: PanelDataArray[];
seriesId: string;
splitByLabel: string;
isSplitByTerms: boolean;
error?: string;
}

export type PanelDataArray = [number | undefined | string, number | string | null];

export interface Annotation {
key: number;
docs: Array<Record<string, string>>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ import moment from 'moment';
import { i18n } from '@kbn/i18n';
import { get } from 'lodash';
import { search } from '../../../../../../plugins/data/public';
const { parseEsInterval } = search.aggs;
import { GTE_INTERVAL_RE } from '../../../../common/interval_regexp';
import { AUTO_INTERVAL } from '../../../../common/constants';
import { isVisTableData } from '../../../../common/vis_data_utils';
import type { PanelData, TimeseriesVisData } from '../../../../common/types';
import { TimeseriesVisParams } from '../../../types';

const { parseEsInterval } = search.aggs;

export const unitLookup = {
s: i18n.translate('visTypeTimeseries.getInterval.secondsLabel', { defaultMessage: 'seconds' }),
m: i18n.translate('visTypeTimeseries.getInterval.minutesLabel', { defaultMessage: 'minutes' }),
Expand Down Expand Up @@ -76,7 +77,11 @@ export const getInterval = (visData: TimeseriesVisData, model: TimeseriesVisPara
) as PanelData[];

return series.reduce((currentInterval, item) => {
if (item.data.length > 1) {
if (
item.data.length > 1 &&
typeof item.data[1][0] === 'number' &&
typeof item.data[0][0] === 'number'
) {
const seriesInterval = item.data[1][0] - item.data[0][0];
if (!currentInterval || seriesInterval < currentInterval) return seriesInterval;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,8 @@
import { i18n } from '@kbn/i18n';
import { get } from 'lodash';

// not typed yet
// @ts-expect-error
import { buildRequestBody } from './table/build_request_body';
import { buildTableRequest } from './table/build_request_body';
import { handleErrorResponse } from './handle_error_response';
// @ts-expect-error
import { processBucket } from './table/process_bucket';

import { createFieldsFetcher } from '../search_strategies/lib/fields_fetcher';
Expand Down Expand Up @@ -74,15 +71,16 @@ export async function getTableData(
const handleError = handleErrorResponse(panel);

try {
const body = await buildRequestBody(
const body = await buildTableRequest({
req,
panel,
services.esQueryConfig,
panelIndex,
esQueryConfig: services.esQueryConfig,
seriesIndex: panelIndex,
capabilities,
services.uiSettings,
() => services.buildSeriesMetaParams(panelIndex, Boolean(panel.use_kibana_indexes))
);
uiSettings: services.uiSettings,
buildSeriesMetaParams: () =>
services.buildSeriesMetaParams(panelIndex, Boolean(panel.use_kibana_indexes)),
});

const [resp] = await searchStrategy.search(requestContext, req, [
{
Expand All @@ -100,9 +98,7 @@ export async function getTableData(
[]
);

const series = await Promise.all(
buckets.map(processBucket(panel, req, searchStrategy, capabilities, extractFields))
);
const series = await Promise.all(buckets.map(processBucket({ panel, extractFields })));

return {
...meta,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
* Side Public License, v 1.
*/

export function formatKey(key, series) {
if (/{{\s*key\s*}}/.test(series.label)) {
import { Series } from '../../../../common/types';

export function formatKey(key: string, series: Series) {
if (series.label && /{{\s*key\s*}}/.test(series.label)) {
return series.label.replace(/{{\s*key\s*}}/, key);
}
return key;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
*/

import { getBucketsPath } from './get_buckets_path';
import type { Metric } from '../../../../common/types';

describe('getBucketsPath', () => {
const metrics = [
const metrics = ([
{ id: 1, type: 'derivative' },
{ id: 2, type: 'percentile', percentiles: [{ value: '50' }] },
{ id: 3, type: 'percentile', percentiles: [{ value: '20.0' }, { value: '10.0' }] },
Expand All @@ -19,45 +20,45 @@ describe('getBucketsPath', () => {
{ id: 7, type: 'sum_of_squares' },
{ id: 8, type: 'variance' },
{ id: 9, type: 'max' },
];
] as unknown) as Metric[];

test('return path for derivative', () => {
expect(getBucketsPath(1, metrics)).toEqual('1[normalized_value]');
expect(getBucketsPath('1', metrics)).toEqual('1[normalized_value]');
});

test('return path for percentile(50)', () => {
expect(getBucketsPath(2, metrics)).toEqual('2[50.0]');
expect(getBucketsPath('2', metrics)).toEqual('2[50.0]');
});

test('return path for percentile(20.0)', () => {
expect(getBucketsPath(3, metrics)).toEqual('3[20.0]');
expect(getBucketsPath('3', metrics)).toEqual('3[20.0]');
});

test('return path for percentile(10.0) with alt id', () => {
expect(getBucketsPath('3[10.0]', metrics)).toEqual('3[10.0]');
});

test('return path for std_deviation(raw)', () => {
expect(getBucketsPath(4, metrics)).toEqual('4[std_deviation]');
expect(getBucketsPath('4', metrics)).toEqual('4[std_deviation]');
});

test('return path for std_deviation(upper)', () => {
expect(getBucketsPath(5, metrics)).toEqual('5[std_upper]');
expect(getBucketsPath('5', metrics)).toEqual('5[std_upper]');
});

test('return path for std_deviation(lower)', () => {
expect(getBucketsPath(6, metrics)).toEqual('6[std_lower]');
expect(getBucketsPath('6', metrics)).toEqual('6[std_lower]');
});

test('return path for sum_of_squares', () => {
expect(getBucketsPath(7, metrics)).toEqual('7[sum_of_squares]');
expect(getBucketsPath('7', metrics)).toEqual('7[sum_of_squares]');
});

test('return path for variance', () => {
expect(getBucketsPath(8, metrics)).toEqual('8[variance]');
expect(getBucketsPath('8', metrics)).toEqual('8[variance]');
});

test('return path for basic metric', () => {
expect(getBucketsPath(9, metrics)).toEqual('9');
expect(getBucketsPath('9', metrics)).toEqual('9');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { startsWith } from 'lodash';
import { toPercentileNumber } from '../../../../common/to_percentile_number';
import { METRIC_TYPES } from '../../../../common/enums';
import type { Metric } from '../../../../common/types';

const percentileTest = /\[[0-9\.]+\]$/;

export const getBucketsPath = (id: string, metrics: Metric[]) => {
const metric = metrics.find((m) => startsWith(id, m.id));
let bucketsPath = String(id);

if (metric) {
switch (metric.type) {
case METRIC_TYPES.DERIVATIVE:
bucketsPath += '[normalized_value]';
break;
// For percentiles we need to breakout the percentile key that the user
// specified. This information is stored in the key using the following pattern
// {metric.id}[{percentile}]
case METRIC_TYPES.PERCENTILE:
if (percentileTest.test(bucketsPath)) break;
if (metric.percentiles?.length) {
const percent = metric.percentiles[0];

bucketsPath += `[${toPercentileNumber(percent.value!)}]`;
}
break;
case METRIC_TYPES.PERCENTILE_RANK:
if (percentileTest.test(bucketsPath)) break;
bucketsPath += `[${toPercentileNumber(metric.value!)}]`;
break;
case METRIC_TYPES.STD_DEVIATION:
case METRIC_TYPES.VARIANCE:
case METRIC_TYPES.SUM_OF_SQUARES:
if (/^std_deviation/.test(metric.type) && ['upper', 'lower'].includes(metric.mode!)) {
bucketsPath += `[std_${metric.mode}]`;
} else {
bucketsPath += `[${metric.type}]`;
}
break;
}
}

return bucketsPath;
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,28 @@
*/

import { getLastMetric } from './get_last_metric';
import type { Series } from '../../../../common/types';

describe('getLastMetric(series)', () => {
test('returns the last metric', () => {
const series = {
const series = ({
metrics: [
{ id: 1, type: 'avg' },
{ id: 2, type: 'moving_average' },
],
};
} as unknown) as Series;

expect(getLastMetric(series)).toEqual({ id: 2, type: 'moving_average' });
});

test('returns the last metric that not a series_agg', () => {
const series = {
const series = ({
metrics: [
{ id: 1, type: 'avg' },
{ id: 2, type: 'series_agg' },
],
};
} as unknown) as Series;

expect(getLastMetric(series)).toEqual({ id: 1, type: 'avg' });
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,9 @@
* Side Public License, v 1.
*/

import { mathAgg } from '../series/math';
import { last } from 'lodash';

export function math(bucket, panel, series, meta, extractFields) {
return (next) => (results) => {
const mathFn = mathAgg({ aggregations: bucket }, panel, series, meta, extractFields);
return mathFn(next)(results);
};
}
import type { Series, Metric } from '../../../../common/types';

export const getLastMetric = (series: Series) =>
last(series.metrics.filter((s) => s.type !== 'series_agg')) as Metric;
Loading

0 comments on commit fcaa4aa

Please sign in to comment.