Skip to content

Commit

Permalink
[Uptime] [Blocker] Move absolute date parsing to URL params hook (#46066
Browse files Browse the repository at this point in the history
) (#46093)

* Move absolute date parsing to URL params hook.

* Clean up naming.

* Update code to avoid putting dynamically-computed values in URL.

* Add test for new helper function.
  • Loading branch information
justinkambic authored Sep 24, 2019
1 parent f497b61 commit 34306fc
Show file tree
Hide file tree
Showing 17 changed files with 143 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
*/

export const CLIENT_DEFAULTS = {
ABSOLUTE_DATE_RANGE_START: 0,
// 15 minutes
ABSOLUTE_DATE_RANGE_END: 1000 * 60 * 15,
// 60 seconds
AUTOREFRESH_INTERVAL: 60 * 1000,
// polling defaults to "on"
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,24 @@
*/

import React from 'react';
import DateMath from '@elastic/datemath';
import { shallowWithIntl } from 'test_utils/enzyme_helpers';
import { MonitorChartsComponent } from '../monitor_charts';
import { MonitorChart } from '../../../../common/graphql/types';

describe('MonitorCharts component', () => {
let dateMathSpy: any;
const MOCK_DATE_VALUE = 20;

beforeEach(() => {
dateMathSpy = jest.spyOn(DateMath, 'parse');
dateMathSpy.mockReturnValue(MOCK_DATE_VALUE);
});

afterEach(() => {
jest.clearAllMocks();
});

const chartResponse: { monitorChartsData: MonitorChart } = {
monitorChartsData: {
locationDurationLines: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ import {
timeFormatter,
} from '@elastic/charts';
import { EuiPanel, EuiTitle } from '@elastic/eui';
import React, { useContext } from 'react';
import React from 'react';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
import { StatusData } from '../../../../common/graphql/types';
import { getChartDateLabel } from '../../../lib/helper';
import { UptimeSettingsContext } from '../../../contexts';
import { getColorsMap } from './get_colors_map';
import { useUrlParams } from '../../../hooks';

interface ChecksChartProps {
/**
Expand All @@ -47,7 +47,8 @@ interface ChecksChartProps {
export const ChecksChart = ({ dangerColor, status, successColor }: ChecksChartProps) => {
const upSeriesSpecId = getSpecId('Up');
const downSeriesSpecId = getSpecId('Down');
const { absoluteStartDate, absoluteEndDate } = useContext(UptimeSettingsContext);
const [getUrlParams] = useUrlParams();
const { absoluteDateRangeStart: min, absoluteDateRangeEnd: max } = getUrlParams();

const upString = i18n.translate('xpack.uptime.monitorCharts.checkStatus.series.upCountLabel', {
defaultMessage: 'Up count',
Expand All @@ -71,12 +72,12 @@ export const ChecksChart = ({ dangerColor, status, successColor }: ChecksChartPr
</EuiTitle>
<EuiPanel>
<Chart>
<Settings xDomain={{ min: absoluteStartDate, max: absoluteEndDate }} showLegend={false} />
<Settings xDomain={{ min, max }} showLegend={false} />
<Axis
id={getAxisId('checksBottom')}
position={Position.Bottom}
showOverlappingTicks={true}
tickFormat={timeFormatter(getChartDateLabel(absoluteStartDate, absoluteEndDate))}
tickFormat={timeFormatter(getChartDateLabel(min, max))}
title={i18n.translate('xpack.uptime.monitorChart.checksChart.bottomAxis.title', {
defaultMessage: 'Timestamp',
description: 'The heading of the x-axis of a chart of timeseries data.',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ import {
Settings,
} from '@elastic/charts';
import { EuiPanel, EuiTitle } from '@elastic/eui';
import React, { useContext } from 'react';
import React from 'react';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
import {
convertMicrosecondsToMilliseconds as microsToMillis,
getChartDateLabel,
} from '../../../lib/helper';
import { LocationDurationLine } from '../../../../common/graphql/types';
import { UptimeSettingsContext } from '../../../contexts';
import { getColorsMap } from './get_colors_map';
import { ChartWrapper } from './chart_wrapper';
import { useUrlParams } from '../../../hooks';

interface DurationChartProps {
/**
Expand Down Expand Up @@ -59,10 +59,10 @@ interface DurationChartProps {
export const DurationChart = ({
locationDurationLines,
meanColor,
rangeColor,
loading,
}: DurationChartProps) => {
const { absoluteStartDate, absoluteEndDate } = useContext(UptimeSettingsContext);
const [getUrlParams] = useUrlParams();
const { absoluteDateRangeStart: min, absoluteDateRangeEnd: max } = getUrlParams();
// this id is used for the line chart representing the average duration length
const averageSpecId = getSpecId('average-');

Expand Down Expand Up @@ -99,16 +99,12 @@ export const DurationChart = ({
</EuiTitle>
<ChartWrapper height="400px" loading={loading}>
<Chart>
<Settings
xDomain={{ min: absoluteStartDate, max: absoluteEndDate }}
showLegend={true}
legendPosition={Position.Bottom}
/>
<Settings xDomain={{ min, max }} showLegend={true} legendPosition={Position.Bottom} />
<Axis
id={getAxisId('bottom')}
position={Position.Bottom}
showOverlappingTicks={true}
tickFormat={timeFormatter(getChartDateLabel(absoluteStartDate, absoluteEndDate))}
tickFormat={timeFormatter(getChartDateLabel(min, max))}
title={i18n.translate('xpack.uptime.monitorCharts.durationChart.bottomAxis.title', {
defaultMessage: 'Timestamp',
})}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
getAxisId,
getSpecId,
Position,
ScaleType,
timeFormatter,
Settings,
} from '@elastic/charts';
Expand Down Expand Up @@ -147,8 +146,7 @@ export const SnapshotHistogramComponent = ({
defaultMessage: 'Snapshot Y Axis',
})
)}
position={Position.Left}
showOverlappingTicks={true}
position="left"
title={i18n.translate('xpack.uptime.snapshotHistogram.yAxis.title', {
defaultMessage: 'Pings',
description:
Expand All @@ -163,9 +161,9 @@ export const SnapshotHistogramComponent = ({
stackAccessors={[0]}
timeZone="local"
xAccessor={0}
xScaleType={ScaleType.Time}
xScaleType="time"
yAccessors={[1]}
yScaleType={ScaleType.Linear}
yScaleType="linear"
/>
<BarSeries
customSeriesColors={getColorsMap(dangerColor, downSpecId)}
Expand All @@ -177,9 +175,9 @@ export const SnapshotHistogramComponent = ({
stackAccessors={[0]}
timeZone="local"
xAccessor={0}
xScaleType={ScaleType.Time}
xScaleType="time"
yAccessors={[1]}
yScaleType={ScaleType.Linear}
yScaleType="linear"
/>
</Chart>
</ChartWrapper>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@
import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import React, { Fragment, useContext } from 'react';
import DateMath from '@elastic/datemath';
import { Moment } from 'moment';
import { MonitorChart } from '../../../common/graphql/types';
import { UptimeGraphQLQueryProps, withUptimeGraphQL } from '../higher_order';
import { monitorChartsQuery } from '../../queries';
import { DurationChart } from './charts';
import { UptimeSettingsContext } from '../../contexts';
import { SnapshotHistogram } from './charts/snapshot_histogram';
import { useUrlParams } from '../../hooks';

interface MonitorChartsQueryResult {
monitorChartsData?: MonitorChart;
Expand Down Expand Up @@ -47,10 +46,9 @@ export const MonitorChartsComponent = ({
} = data;

const { colors } = useContext(UptimeSettingsContext);
const parseDateRange = (r: string): number => {
const parsed: Moment | undefined = DateMath.parse(r);
return parsed ? parsed.valueOf() : 0;
};
const [getUrlParams] = useUrlParams();
const { absoluteDateRangeStart, absoluteDateRangeEnd } = getUrlParams();

return (
<Fragment>
<EuiFlexGroup>
Expand All @@ -64,8 +62,8 @@ export const MonitorChartsComponent = ({
</EuiFlexItem>
<EuiFlexItem>
<SnapshotHistogram
absoluteStartDate={parseDateRange(dateRangeStart)}
absoluteEndDate={parseDateRange(dateRangeEnd)}
absoluteStartDate={absoluteDateRangeStart}
absoluteEndDate={absoluteDateRangeEnd}
successColor={colors.success}
dangerColor={colors.danger}
variables={{ dateRangeStart, dateRangeEnd, monitorId }}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import { mountWithIntl } from 'test_utils/enzyme_helpers';
import DateMath from '@elastic/datemath';
import React, { useState, Fragment } from 'react';
import { useUrlParams, UptimeUrlParamsHook } from '../use_url_params';
import { RouteComponentProps } from 'react-router';
Expand Down Expand Up @@ -38,6 +39,8 @@ const UseUrlParamsTestComponent = ({ hook }: MockUrlParamsComponentProps) => {
};

describe('useUrlParams', () => {
let dateMathSpy: any;
const MOCK_DATE_VALUE = 20;
beforeEach(() => {
mockRouter = {
// @ts-ignore other properties aren't needed for this test
Expand All @@ -57,6 +60,8 @@ describe('useUrlParams', () => {
url: 'http://elastic.co',
},
};
dateMathSpy = jest.spyOn(DateMath, 'parse');
dateMathSpy.mockReturnValue(MOCK_DATE_VALUE);
});

it('accepts router props, updates URL params, and returns the current params', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
import qs from 'querystring';
import { UptimeUrlParams } from './url_params/get_supported_url_params';

export const stringifyUrlParams = (params: UptimeUrlParams) => `?${qs.stringify(params)}`;
export const stringifyUrlParams = (params: Partial<UptimeUrlParams>) => `?${qs.stringify(params)}`;

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,29 @@
* you may not use this file except in compliance with the Elastic License.
*/

import DateMath from '@elastic/datemath';
import { getSupportedUrlParams } from '../get_supported_url_params';
import { CLIENT_DEFAULTS } from '../../../../../common/constants';

describe('getSupportedUrlParams', () => {
let dateMathSpy: any;
const MOCK_DATE_VALUE = 20;

beforeEach(() => {
dateMathSpy = jest.spyOn(DateMath, 'parse');
dateMathSpy.mockReturnValue(MOCK_DATE_VALUE);
});

afterEach(() => {
jest.clearAllMocks();
});

it('returns custom values', () => {
const customValues = {
autorefreshInterval: '23',
autorefreshIsPaused: 'false',
dateRangeStart: 'foo',
dateRangeEnd: 'bar',
dateRangeStart: 'now-15m',
dateRangeEnd: 'now',
monitorListPageIndex: '23',
monitorListPageSize: '50',
monitorListSortDirection: 'desc',
Expand All @@ -39,6 +52,8 @@ describe('getSupportedUrlParams', () => {
const result = getSupportedUrlParams({});
expect(result).toMatchSnapshot();
expect(result).toEqual({
absoluteDateRangeStart: MOCK_DATE_VALUE,
absoluteDateRangeEnd: MOCK_DATE_VALUE,
autorefreshInterval: AUTOREFRESH_INTERVAL,
autorefreshIsPaused: AUTOREFRESH_IS_PAUSED,
dateRangeStart: DATE_RANGE_START,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import DateMath from '@elastic/datemath';
import moment from 'moment';
import { parseAbsoluteDate } from '../parse_absolute_date';

describe('parseAbsoluteDate', () => {
let dateMathSpy: any;
const MOCK_VALUE = 132435465789;

beforeEach(() => {
dateMathSpy = jest.spyOn(DateMath, 'parse');
dateMathSpy.mockReturnValue(moment(MOCK_VALUE));
});

it('returns the parsed value for a valid date string', () => {
const result = parseAbsoluteDate('now-15m', 12345);
expect(result).toBe(MOCK_VALUE);
});

it('returns the default value if the parser provides `undefined`', () => {
dateMathSpy.mockReturnValue(undefined);
const result = parseAbsoluteDate('this is not a valid datae', 12345);
expect(result).toBe(12345);
});
});
Loading

0 comments on commit 34306fc

Please sign in to comment.