Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dateHistogramInterval utility #37108

Closed
wants to merge 17 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/eslint-config-kibana/jest.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module.exports = {
{
files: [
'**/*.{test,test.mocks,mock}.{js,ts,tsx}',
'**/__mocks__/**/*.{js,ts,tsx}',
],
plugins: [
'jest',
Expand Down
2 changes: 1 addition & 1 deletion src/dev/jest/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export default {
'!src/legacy/core_plugins/**/__snapshots__/**/*',
],
moduleNameMapper: {
'^plugins/([^\/.]*)/(.*)': '<rootDir>/src/legacy/core_plugins/$1/public/$2',
'^plugins/([^\/.]*)(.*)': '<rootDir>/src/legacy/core_plugins/$1/public$2',
'^ui/(.*)': '<rootDir>/src/legacy/ui/public/$1',
'^uiExports/(.*)': '<rootDir>/src/dev/jest/mocks/file_mock.js',
'^test_utils/(.*)': '<rootDir>/src/test_utils/public/$1',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* 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 { dateHistogramInterval } from './date_histogram_interval';

describe('dateHistogramInterval', () => {
it('should return calender_interval key for calendar intervals', () => {
expect(dateHistogramInterval('1m')).toEqual({ calendar_interval: '1m' });
expect(dateHistogramInterval('1h')).toEqual({ calendar_interval: '1h' });
expect(dateHistogramInterval('1d')).toEqual({ calendar_interval: '1d' });
expect(dateHistogramInterval('1w')).toEqual({ calendar_interval: '1w' });
expect(dateHistogramInterval('1M')).toEqual({ calendar_interval: '1M' });
expect(dateHistogramInterval('1y')).toEqual({ calendar_interval: '1y' });
});

it('should return fixed_interval key for fixed intervals', () => {
expect(dateHistogramInterval('1ms')).toEqual({ fixed_interval: '1ms' });
expect(dateHistogramInterval('42ms')).toEqual({ fixed_interval: '42ms' });
expect(dateHistogramInterval('1s')).toEqual({ fixed_interval: '1s' });
expect(dateHistogramInterval('42s')).toEqual({ fixed_interval: '42s' });
expect(dateHistogramInterval('42m')).toEqual({ fixed_interval: '42m' });
expect(dateHistogramInterval('42h')).toEqual({ fixed_interval: '42h' });
expect(dateHistogramInterval('42d')).toEqual({ fixed_interval: '42d' });
});

it('should throw an error on invalid intervals', () => {
expect(() => dateHistogramInterval('2w')).toThrow();
expect(() => dateHistogramInterval('2M')).toThrow();
expect(() => dateHistogramInterval('2y')).toThrow();
expect(() => dateHistogramInterval('2')).toThrow();
expect(() => dateHistogramInterval('y')).toThrow();
expect(() => dateHistogramInterval('0.5h')).toThrow();
});
});
49 changes: 49 additions & 0 deletions src/legacy/core_plugins/data/common/date_histogram_interval.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* 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 { parseEsInterval } from './parse_es_interval';

type Interval = { fixed_interval: string } | { calendar_interval: string };

/**
* Checks whether a given Elasticsearch interval is a calendar or fixed interval
* and returns an object containing the appropriate date_histogram property for that
* interval. So it will return either an object containing the fixed_interval key for
* that interval or a calendar_interval. If the specified interval was not a valid Elasticsearch
* interval this method will throw an error.
*
* You can simply spread the returned value of this method into your date_histogram.
* @example
* const aggregation = {
* date_histogram: {
* field: 'date',
* ...dateHistogramInterval('24h'),
* }
* };
*
* @param interval The interval string to return the appropriate date_histogram key for.
*/
export function dateHistogramInterval(interval: string): Interval {
const { type } = parseEsInterval(interval);
if (type === 'calendar') {
return { calendar_interval: interval };
} else {
return { fixed_interval: interval };
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@
export { parseEsInterval, ParsedInterval } from './parse_es_interval';
export { InvalidEsCalendarIntervalError } from './invalid_es_calendar_interval_error';
export { InvalidEsIntervalFormatError } from './invalid_es_interval_format_error';
export { isValidEsInterval } from './is_valid_es_interval';
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class InvalidEsCalendarIntervalError extends Error {
public readonly type: string
) {
super(
i18n.translate('common.ui.parseEsInterval.invalidEsCalendarIntervalErrorMessage', {
i18n.translate('data.parseEsInterval.invalidEsCalendarIntervalErrorMessage', {
defaultMessage: 'Invalid calendar interval: {interval}, value must be 1',
values: { interval },
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { i18n } from '@kbn/i18n';
export class InvalidEsIntervalFormatError extends Error {
constructor(public readonly interval: string) {
super(
i18n.translate('common.ui.parseEsInterval.invalidEsIntervalFormatErrorMessage', {
i18n.translate('data.parseEsInterval.invalidEsIntervalFormatErrorMessage', {
defaultMessage: 'Invalid interval format: {interval}',
values: { interval },
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* 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 { parseEsInterval } from './parse_es_interval';

/**
* Checks whether a given interval string (e.g. 1w, 24h, ...) is a valid Elasticsearch interval.
* Will return false if the interval is not valid in Elasticsearch, otherwise true.
* Invalid intervals might be: 2f, since there is no unit 'f'; 2w, since weeks and month intervals
* are only allowed with a value of 1, etc.
*
* @param interval The interval string like 1w, 24h
* @returns True if the interval is valid for Elasticsearch
*/
export function isValidEsInterval(interval: string): boolean {
try {
parseEsInterval(interval);
return true;
} catch {
return false;
}
}
15 changes: 14 additions & 1 deletion src/legacy/core_plugins/data/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class DataPlugin {
*/
export const data = new DataPlugin().setup();

/** @public */
/** @public types */
export interface DataSetup {
expressions: ExpressionsSetup;
indexPatterns: IndexPatternsSetup;
Expand All @@ -92,4 +92,17 @@ export { ExpressionRenderer, ExpressionRendererProps, ExpressionRunner } from '.

/** @public types */
export { IndexPattern, StaticIndexPattern, StaticIndexPatternField, Field } from './index_patterns';

/** @public static code */
export { dateHistogramInterval } from '../common/date_histogram_interval';

/** @public static code */
export {
isValidEsInterval,
InvalidEsCalendarIntervalError,
InvalidEsIntervalFormatError,
parseEsInterval,
ParsedInterval,
} from '../common/parse_es_interval';

export { Query } from './query';
30 changes: 30 additions & 0 deletions src/legacy/core_plugins/data/server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* 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.
*/

/** @public static code */
export { dateHistogramInterval } from '../common/date_histogram_interval';

/** @public static code */
export {
isValidEsInterval,
InvalidEsCalendarIntervalError,
InvalidEsIntervalFormatError,
parseEsInterval,
ParsedInterval,
} from '../common/parse_es_interval';
Original file line number Diff line number Diff line change
@@ -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.
*/

/* eslint-env jest */

const interpreter = {
getInterpreter: jest.fn().mockReturnValue(Promise.resolve({ interpreter: jest.fn() })),
interpretAst: jest.fn(),
};

// eslint-disable-next-line import/no-default-export
export default interpreter;
1 change: 1 addition & 0 deletions src/legacy/core_plugins/tests_bundle/find_source_files.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const findSourceFiles = async (patterns, cwd = fromRoot('.')) => {
'bower_components/**/*',
'**/_*.js',
'**/*.test.js',
'**/__mocks__/**/*',
'**/*.test.mocks.js',
],
symlinks: findSourceFiles.symlinks,
Expand Down
15 changes: 15 additions & 0 deletions src/legacy/ui/public/__mocks__/ui/chrome.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,18 @@
* specific language governing permissions and limitations
* under the License.
*/

import { uiSettingsServiceMock } from '../../../../../core/public/mocks';

const chrome = {
getBasePath: jest.fn().mockReturnValue(''),
getUiSettingsClient: () => ({
...uiSettingsServiceMock.createSetupContract(),
getUpdate$: () => ({
subscribe: jest.fn(),
}),
}),
};

// eslint-disable-next-line import/no-default-export
export default chrome;
25 changes: 25 additions & 0 deletions src/legacy/ui/public/__mocks__/ui/metadata.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* 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.
*/

const metadata = {
branch: 'test',
version: '42.0.0',
};

export { metadata };
22 changes: 22 additions & 0 deletions src/legacy/ui/public/__mocks__/ui/utils/legacy_class.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* 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 const createLegacyClass = () => ({
inherits: jest.fn(),
});
Loading