From c4f0ca14bc0455fa03920fa8323bf44482fc6bd6 Mon Sep 17 00:00:00 2001 From: shahzad Date: Wed, 11 Mar 2020 11:34:41 +0100 Subject: [PATCH 1/8] use kibana http --- .../uptime/common/constants/rest_api.ts | 18 ++++++ .../parameterize_values.test.ts.snap | 5 -- .../lib/helper/__tests__/get_api_path.test.ts | 24 -------- .../__tests__/parameterize_values.test.ts | 30 ---------- .../uptime/public/lib/helper/get_api_path.ts | 8 --- .../plugins/uptime/public/lib/helper/index.ts | 2 - .../public/lib/helper/parameterize_values.ts | 16 ------ .../__snapshots__/snapshot.test.ts.snap | 6 +- .../state/api/__tests__/snapshot.test.ts | 28 ++++++---- .../uptime/public/state/api/index_pattern.ts | 17 ++---- .../uptime/public/state/api/monitor.ts | 33 +++-------- .../public/state/api/monitor_duration.ts | 23 ++------ .../uptime/public/state/api/monitor_status.ts | 30 +++------- .../public/state/api/overview_filters.ts | 36 +++++------- .../plugins/uptime/public/state/api/ping.ts | 17 ++---- .../uptime/public/state/api/snapshot.ts | 20 +++---- .../plugins/uptime/public/state/api/types.ts | 1 - .../plugins/uptime/public/state/api/utils.ts | 55 +++++++++++++++++++ .../public/state/effects/fetch_effect.ts | 3 + .../public/state/reducers/overview_filters.ts | 1 + .../plugins/uptime/public/uptime_app.tsx | 3 + .../index_pattern/get_index_pattern.ts | 3 +- .../rest_api/monitors/monitor_locations.ts | 3 +- .../rest_api/monitors/monitors_details.ts | 3 +- .../rest_api/monitors/monitors_durations.ts | 3 + .../uptime/server/rest_api/monitors/status.ts | 7 ++- .../overview_filters/get_overview_filters.ts | 3 +- .../uptime/server/rest_api/pings/get_all.ts | 3 +- .../rest_api/pings/get_ping_histogram.ts | 3 +- .../uptime/server/rest_api/pings/get_pings.ts | 3 +- .../rest_api/snapshot/get_snapshot_count.ts | 3 +- 31 files changed, 175 insertions(+), 235 deletions(-) create mode 100644 x-pack/legacy/plugins/uptime/common/constants/rest_api.ts delete mode 100644 x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/__snapshots__/parameterize_values.test.ts.snap delete mode 100644 x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/get_api_path.test.ts delete mode 100644 x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/parameterize_values.test.ts delete mode 100644 x-pack/legacy/plugins/uptime/public/lib/helper/get_api_path.ts delete mode 100644 x-pack/legacy/plugins/uptime/public/lib/helper/parameterize_values.ts create mode 100644 x-pack/legacy/plugins/uptime/public/state/api/utils.ts diff --git a/x-pack/legacy/plugins/uptime/common/constants/rest_api.ts b/x-pack/legacy/plugins/uptime/common/constants/rest_api.ts new file mode 100644 index 00000000000000..15b78deae708a8 --- /dev/null +++ b/x-pack/legacy/plugins/uptime/common/constants/rest_api.ts @@ -0,0 +1,18 @@ +/* + * 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. + */ + +export enum API_URLS { + INDEX_PATTERN = `/api/uptime/index_pattern`, + MONITOR_LOCATIONS = `/api/uptime/monitor/locations`, + MONITOR_DURATION = `/api/uptime/monitor/duration`, + MONITOR_DETAILS = `/api/uptime/monitor/details`, + MONITOR_SELECTED = `/api/uptime/monitor/selected`, + MONITOR_STATUS = `/api/uptime/monitor/status`, + PINGS = '/api/uptime/pings', + PING_HISTOGRAM = `/api/uptime/ping/histogram`, + SNAPSHOT_COUNT = `/api/uptime/snapshot/count`, + FILTERS = `/api/uptime/filters`, +} diff --git a/x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/__snapshots__/parameterize_values.test.ts.snap b/x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/__snapshots__/parameterize_values.test.ts.snap deleted file mode 100644 index 39c28a87f5e71f..00000000000000 --- a/x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/__snapshots__/parameterize_values.test.ts.snap +++ /dev/null @@ -1,5 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`parameterizeValues parameterizes provided values for multiple fields 1`] = `"foo=bar&foo=baz&bar=foo&bar=baz"`; - -exports[`parameterizeValues parameterizes the provided values for a given field name 1`] = `"foo=bar&foo=baz"`; diff --git a/x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/get_api_path.test.ts b/x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/get_api_path.test.ts deleted file mode 100644 index c111008fdc3d19..00000000000000 --- a/x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/get_api_path.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* - * 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 { getApiPath } from '../get_api_path'; - -describe('getApiPath', () => { - it('returns a path with basePath when provided', () => { - const result = getApiPath('/api/foo/bar', '/somebasepath'); - expect(result).toEqual('/somebasepath/api/foo/bar'); - }); - - it('returns a valid path when no basePath present', () => { - const result = getApiPath('/api/foo/bar'); - expect(result).toEqual('/api/foo/bar'); - }); - - it('returns a valid path when an empty string is supplied as basePath', () => { - const result = getApiPath('/api/foo/bar', ''); - expect(result).toEqual('/api/foo/bar'); - }); -}); diff --git a/x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/parameterize_values.test.ts b/x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/parameterize_values.test.ts deleted file mode 100644 index e550a1a6397e39..00000000000000 --- a/x-pack/legacy/plugins/uptime/public/lib/helper/__tests__/parameterize_values.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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 { parameterizeValues } from '../parameterize_values'; - -describe('parameterizeValues', () => { - let params: URLSearchParams; - - beforeEach(() => { - params = new URLSearchParams(); - }); - - it('parameterizes the provided values for a given field name', () => { - parameterizeValues(params, { foo: ['bar', 'baz'] }); - expect(params.toString()).toMatchSnapshot(); - }); - - it('parameterizes provided values for multiple fields', () => { - parameterizeValues(params, { foo: ['bar', 'baz'], bar: ['foo', 'baz'] }); - expect(params.toString()).toMatchSnapshot(); - }); - - it('returns an empty string when there are no values provided', () => { - parameterizeValues(params, { foo: [] }); - expect(params.toString()).toBe(''); - }); -}); diff --git a/x-pack/legacy/plugins/uptime/public/lib/helper/get_api_path.ts b/x-pack/legacy/plugins/uptime/public/lib/helper/get_api_path.ts deleted file mode 100644 index 398d58f8460bab..00000000000000 --- a/x-pack/legacy/plugins/uptime/public/lib/helper/get_api_path.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * 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. - */ - -export const getApiPath = (path: string, basePath?: string) => - basePath ? `${basePath}${path}` : path; diff --git a/x-pack/legacy/plugins/uptime/public/lib/helper/index.ts b/x-pack/legacy/plugins/uptime/public/lib/helper/index.ts index ef191ce32e5321..e2aa4a2b3d429a 100644 --- a/x-pack/legacy/plugins/uptime/public/lib/helper/index.ts +++ b/x-pack/legacy/plugins/uptime/public/lib/helper/index.ts @@ -7,9 +7,7 @@ export { combineFiltersAndUserSearch } from './combine_filters_and_user_search'; export { convertMicrosecondsToMilliseconds } from './convert_measurements'; export * from './observability_integration'; -export { getApiPath } from './get_api_path'; export { getChartDateLabel } from './charts'; -export { parameterizeValues } from './parameterize_values'; export { seriesHasDownValues } from './series_has_down_values'; export { stringifyKueries } from './stringify_kueries'; export { UptimeUrlParams, getSupportedUrlParams } from './url_params'; diff --git a/x-pack/legacy/plugins/uptime/public/lib/helper/parameterize_values.ts b/x-pack/legacy/plugins/uptime/public/lib/helper/parameterize_values.ts deleted file mode 100644 index 4c9fa6838c2eda..00000000000000 --- a/x-pack/legacy/plugins/uptime/public/lib/helper/parameterize_values.ts +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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. - */ - -export const parameterizeValues = ( - params: URLSearchParams, - obj: Record -): void => { - Object.keys(obj).forEach(key => { - obj[key].forEach(val => { - params.append(key, val); - }); - }); -}; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/__snapshots__/snapshot.test.ts.snap b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/__snapshots__/snapshot.test.ts.snap index 0d2392390c7e40..575355df79227f 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/__snapshots__/snapshot.test.ts.snap +++ b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/__snapshots__/snapshot.test.ts.snap @@ -1,7 +1,3 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`snapshot API throws when server response doesn't correspond to expected type 1`] = ` -[Error: Invalid value undefined supplied to : { down: number, total: number, up: number }/down: number -Invalid value undefined supplied to : { down: number, total: number, up: number }/total: number -Invalid value undefined supplied to : { down: number, total: number, up: number }/up: number] -`; +exports[`snapshot API throws when server response doesn't correspond to expected type 1`] = `[Error: \`getSnapshotCount\` response did not correspond to expected type]`; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts index e9b1391a23e32a..fe99f4a656b69c 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts @@ -5,17 +5,20 @@ */ import { fetchSnapshotCount } from '../snapshot'; +import { apiService } from '../utils'; +import { HttpFetchError } from '../../../../../../../../src/core/public/http/http_fetch_error'; +import { message } from 'fp-ts/lib/Exception'; describe('snapshot API', () => { let fetchMock: jest.SpyInstance>>; let mockResponse: Partial; beforeEach(() => { - fetchMock = jest.spyOn(window, 'fetch'); - mockResponse = { - ok: true, - json: () => new Promise(r => r({ up: 3, down: 12, total: 15 })), + apiService.http = { + get: jest.fn(), }; + fetchMock = jest.spyOn(apiService.http, 'get'); + mockResponse = { up: 3, down: 12, total: 15 }; }); afterEach(() => { @@ -31,14 +34,19 @@ describe('snapshot API', () => { filters: 'monitor.id:"auto-http-0X21EE76EAC459873F"', statusFilter: 'up', }); - expect(fetchMock).toHaveBeenCalledWith( - '/api/uptime/snapshot/count?dateRangeStart=now-15m&dateRangeEnd=now&filters=monitor.id%3A%22auto-http-0X21EE76EAC459873F%22&statusFilter=up' - ); + expect(fetchMock).toHaveBeenCalledWith('/api/uptime/snapshot/count', { + query: { + dateRangeEnd: 'now', + dateRangeStart: 'now-15m', + filters: 'monitor.id:"auto-http-0X21EE76EAC459873F"', + statusFilter: 'up', + }, + }); expect(resp).toEqual({ up: 3, down: 12, total: 15 }); }); it(`throws when server response doesn't correspond to expected type`, async () => { - mockResponse = { ok: true, json: () => new Promise(r => r({ foo: 'bar' })) }; + mockResponse = { foo: 'bar' }; fetchMock.mockReturnValue(new Promise(r => r(mockResponse))); let error: Error | undefined; try { @@ -56,8 +64,8 @@ describe('snapshot API', () => { }); it('throws an error when response is not ok', async () => { - mockResponse = { ok: false, statusText: 'There was an error fetching your data.' }; - fetchMock.mockReturnValue(new Promise(r => r(mockResponse))); + mockResponse = new HttpFetchError('There was an error fetching your data.', 'error', {}); + fetchMock.mockReturnValue(mockResponse); let error: Error | undefined; try { await fetchSnapshotCount({ diff --git a/x-pack/legacy/plugins/uptime/public/state/api/index_pattern.ts b/x-pack/legacy/plugins/uptime/public/state/api/index_pattern.ts index 2669376d728ab6..c440b8ad758cd7 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/index_pattern.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/index_pattern.ts @@ -4,18 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getApiPath } from '../../lib/helper'; +import { API_URLS } from '../../../common/constants/rest_api'; +import { apiService } from './utils'; -interface APIParams { - basePath: string; -} - -export const fetchIndexPattern = async ({ basePath }: APIParams) => { - const url = getApiPath(`/api/uptime/index_pattern`, basePath); - - const response = await fetch(url); - if (!response.ok) { - throw new Error(response.statusText); - } - return await response.json(); +export const fetchIndexPattern = async () => { + return await apiService.get(API_URLS.INDEX_PATTERN); }; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/monitor.ts b/x-pack/legacy/plugins/uptime/public/state/api/monitor.ts index 80fd311c3ec7e8..209d2e5e270204 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/monitor.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/monitor.ts @@ -5,7 +5,6 @@ */ import { PathReporter } from 'io-ts/lib/PathReporter'; -import { getApiPath } from '../../lib/helper'; import { BaseParams } from './types'; import { MonitorDetailsType, @@ -14,61 +13,45 @@ import { MonitorLocationsType, } from '../../../common/runtime_types'; import { QueryParams } from '../actions/types'; +import { apiService } from './utils'; +import { API_URLS } from '../../../common/constants/rest_api'; interface ApiRequest { monitorId: string; - basePath: string; } export type MonitorQueryParams = BaseParams & ApiRequest; export const fetchMonitorDetails = async ({ monitorId, - basePath, dateStart, dateEnd, }: MonitorQueryParams): Promise => { - const url = getApiPath(`/api/uptime/monitor/details`, basePath); const params = { monitorId, dateStart, dateEnd, }; - const urlParams = new URLSearchParams(params).toString(); - const response = await fetch(`${url}?${urlParams}`); + const response = await apiService.get(API_URLS.MONITOR_DETAILS, params); - if (!response.ok) { - throw new Error(response.statusText); - } - return response.json().then(data => { - PathReporter.report(MonitorDetailsType.decode(data)); - return data; - }); + PathReporter.report(MonitorDetailsType.decode(response)); + return response; }; type ApiParams = QueryParams & ApiRequest; export const fetchMonitorLocations = async ({ monitorId, - basePath, dateStart, dateEnd, }: ApiParams): Promise => { - const url = getApiPath(`/api/uptime/monitor/locations`, basePath); - const params = { dateStart, dateEnd, monitorId, }; - const urlParams = new URLSearchParams(params).toString(); - const response = await fetch(`${url}?${urlParams}`); + const response = await apiService.get(API_URLS.MONITOR_LOCATIONS, params); - if (!response.ok) { - throw new Error(response.statusText); - } - return response.json().then(data => { - PathReporter.report(MonitorLocationsType.decode(data)); - return data; - }); + PathReporter.report(MonitorLocationsType.decode(response)); + return response; }; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/monitor_duration.ts b/x-pack/legacy/plugins/uptime/public/state/api/monitor_duration.ts index 44e797457e5fda..daf725119fcf31 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/monitor_duration.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/monitor_duration.ts @@ -4,29 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -import { stringify } from 'query-string'; - -import { getApiPath } from '../../lib/helper'; import { BaseParams } from './types'; +import { apiService } from './utils'; +import { API_URLS } from '../../../common/constants/rest_api'; -export const fetchMonitorDuration = async ({ - basePath, - monitorId, - dateStart, - dateEnd, -}: BaseParams) => { - const url = getApiPath(`/api/uptime/monitor/duration`, basePath); - - const params = { +export const fetchMonitorDuration = async ({ monitorId, dateStart, dateEnd }: BaseParams) => { + const queryParams = { monitorId, dateStart, dateEnd, }; - const urlParams = stringify(params); - const response = await fetch(`${url}?${urlParams}`); - if (!response.ok) { - throw new Error(response.statusText); - } - return await response.json(); + return await apiService.get(API_URLS.MONITOR_DURATION, queryParams); }; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/monitor_status.ts b/x-pack/legacy/plugins/uptime/public/state/api/monitor_status.ts index 936e864b75619a..d78067c7c18ea7 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/monitor_status.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/monitor_status.ts @@ -4,46 +4,34 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getApiPath } from '../../lib/helper'; import { QueryParams } from '../actions/types'; import { Ping } from '../../../common/graphql/types'; +import { apiService } from './utils'; +import { API_URLS } from '../../../common/constants/rest_api'; export interface APIParams { basePath: string; monitorId: string; } -export const fetchSelectedMonitor = async ({ basePath, monitorId }: APIParams): Promise => { - const url = getApiPath(`/api/uptime/monitor/selected`, basePath); - const params = { +export const fetchSelectedMonitor = async ({ monitorId }: APIParams): Promise => { + const queryParams = { monitorId, }; - const urlParams = new URLSearchParams(params).toString(); - const response = await fetch(`${url}?${urlParams}`); - if (!response.ok) { - throw new Error(response.statusText); - } - const responseData = await response.json(); - return responseData; + + return await apiService.get(API_URLS.MONITOR_SELECTED, queryParams); }; export const fetchMonitorStatus = async ({ - basePath, monitorId, dateStart, dateEnd, }: QueryParams & APIParams): Promise => { - const url = getApiPath(`/api/uptime/monitor/status`, basePath); - const params = { + const queryParams = { monitorId, dateStart, dateEnd, }; - const urlParams = new URLSearchParams(params).toString(); - const response = await fetch(`${url}?${urlParams}`); - if (!response.ok) { - throw new Error(response.statusText); - } - const responseData = await response.json(); - return responseData; + + return await apiService.get(API_URLS.MONITOR_STATUS, queryParams); }; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/overview_filters.ts b/x-pack/legacy/plugins/uptime/public/state/api/overview_filters.ts index c3ef62fa88dcf4..8eeca80c50f14e 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/overview_filters.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/overview_filters.ts @@ -4,18 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ThrowReporter } from 'io-ts/lib/ThrowReporter'; +import { PathReporter } from 'io-ts/lib/PathReporter'; import { isRight } from 'fp-ts/lib/Either'; import { GetOverviewFiltersPayload } from '../actions/overview_filters'; -import { getApiPath, parameterizeValues } from '../../lib/helper'; import { OverviewFiltersType } from '../../../common/runtime_types'; - -type ApiRequest = GetOverviewFiltersPayload & { - basePath: string; -}; +import { apiService } from './utils'; +import { API_URLS } from '../../../common/constants/rest_api'; export const fetchOverviewFilters = async ({ - basePath, dateRangeStart, dateRangeEnd, search, @@ -23,28 +19,22 @@ export const fetchOverviewFilters = async ({ locations, ports, tags, -}: ApiRequest) => { - const url = getApiPath(`/api/uptime/filters`, basePath); - - const params = new URLSearchParams({ +}: GetOverviewFiltersPayload) => { + const queryParams = { dateRangeStart, dateRangeEnd, - }); + schemes, + locations, + ports, + tags, + search, + }; - if (search) { - params.append('search', search); - } - - parameterizeValues(params, { schemes, locations, ports, tags }); + const responseData = await apiService.get(API_URLS.FILTERS, queryParams); - const response = await fetch(`${url}?${params.toString()}`); - if (!response.ok) { - throw new Error(response.statusText); - } - const responseData = await response.json(); const decoded = OverviewFiltersType.decode(responseData); - ThrowReporter.report(decoded); + PathReporter.report(decoded); if (isRight(decoded)) { return decoded.right; } diff --git a/x-pack/legacy/plugins/uptime/public/state/api/ping.ts b/x-pack/legacy/plugins/uptime/public/state/api/ping.ts index c61bf42c8c90e8..df71cc8d67bd07 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/ping.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/ping.ts @@ -4,32 +4,25 @@ * you may not use this file except in compliance with the Elastic License. */ -import { stringify } from 'query-string'; -import { getApiPath } from '../../lib/helper'; import { APIFn } from './types'; import { GetPingHistogramParams, HistogramResult } from '../../../common/types'; +import { apiService } from './utils'; +import { API_URLS } from '../../../common/constants/rest_api'; export const fetchPingHistogram: APIFn = async ({ - basePath, monitorId, dateStart, dateEnd, statusFilter, filters, }) => { - const url = getApiPath(`/api/uptime/ping/histogram`, basePath); - const params = { + const queryParams = { dateStart, dateEnd, ...(monitorId && { monitorId }), ...(statusFilter && { statusFilter }), ...(filters && { filters }), }; - const urlParams = stringify(params, { sort: false }); - const response = await fetch(`${url}?${urlParams}`); - if (!response.ok) { - throw new Error(response.statusText); - } - const responseData = await response.json(); - return responseData; + + return await apiService.get(API_URLS.PING_HISTOGRAM, queryParams); }; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/snapshot.ts b/x-pack/legacy/plugins/uptime/public/state/api/snapshot.ts index cbfe00a4a87467..048cf264a93b12 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/snapshot.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/snapshot.ts @@ -4,10 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ThrowReporter } from 'io-ts/lib/ThrowReporter'; import { isRight } from 'fp-ts/lib/Either'; -import { getApiPath } from '../../lib/helper'; +import { PathReporter } from 'io-ts/lib/PathReporter'; import { SnapshotType, Snapshot } from '../../../common/runtime_types'; +import { apiService } from './utils'; +import { API_URLS } from '../../../common/constants/rest_api'; interface ApiRequest { basePath: string; @@ -18,27 +19,22 @@ interface ApiRequest { } export const fetchSnapshotCount = async ({ - basePath, dateRangeStart, dateRangeEnd, filters, statusFilter, }: ApiRequest): Promise => { - const url = getApiPath(`/api/uptime/snapshot/count`, basePath); - const params = { + const queryParams = { dateRangeStart, dateRangeEnd, ...(filters && { filters }), ...(statusFilter && { statusFilter }), }; - const urlParams = new URLSearchParams(params).toString(); - const response = await fetch(`${url}?${urlParams}`); - if (!response.ok) { - throw new Error(response.statusText); - } - const responseData = await response.json(); + + const responseData = await apiService.get(API_URLS.SNAPSHOT_COUNT, queryParams); + const decoded = SnapshotType.decode(responseData); - ThrowReporter.report(decoded); + PathReporter.report(decoded); if (isRight(decoded)) { return decoded.right; } diff --git a/x-pack/legacy/plugins/uptime/public/state/api/types.ts b/x-pack/legacy/plugins/uptime/public/state/api/types.ts index a148f1c7d7ae37..e54275d30d51e4 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/types.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/types.ts @@ -5,7 +5,6 @@ */ export interface BaseParams { - basePath: string; dateStart: string; dateEnd: string; filters?: string; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/utils.ts b/x-pack/legacy/plugins/uptime/public/state/api/utils.ts new file mode 100644 index 00000000000000..5ab17ee17c67ce --- /dev/null +++ b/x-pack/legacy/plugins/uptime/public/state/api/utils.ts @@ -0,0 +1,55 @@ +/* + * 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 { HttpFetchQuery, HttpSetup } from '../../../../../../../target/types/core/public'; + +class ApiService { + private static instance: ApiService; + public http: HttpSetup; + + public set http(httpSetup: HttpSetup) { + this.http = httpSetup; + } + + private constructor() {} + + static getInstance(): ActionsBus { + if (!ApiService.instance) { + ApiService.instance = new ApiService(); + } + + return ApiService.instance; + } + + public async get(apiUrl: string, params: HttpFetchQuery) { + const response = await this.http!.get(apiUrl, { query: params }); + if (response instanceof Error) { + throw response; + } + return response; + } + + public async post(apiUrl: string, data: any) { + const response = await this.http!.post(apiUrl, { + method: 'POST', + body: JSON.stringify(data), + }); + if (response instanceof Error) { + throw response; + } + return response; + } + + public async delete(apiUrl: string) { + const response = await this.http!.delete(apiUrl); + if (response instanceof Error) { + throw response; + } + return response; + } +} + +export const apiService = ApiService.getInstance(); diff --git a/x-pack/legacy/plugins/uptime/public/state/effects/fetch_effect.ts b/x-pack/legacy/plugins/uptime/public/state/effects/fetch_effect.ts index d293cdbe451b54..4ca61c70dfa828 100644 --- a/x-pack/legacy/plugins/uptime/public/state/effects/fetch_effect.ts +++ b/x-pack/legacy/plugins/uptime/public/state/effects/fetch_effect.ts @@ -37,6 +37,9 @@ export function fetchEffectFactory( const response = yield call(fetch, { ...params, basePath }); yield put(success(response)); } catch (error) { + // eslint-disable-next-line no-console + console.error(error); + yield put(fail(error)); } }; diff --git a/x-pack/legacy/plugins/uptime/public/state/reducers/overview_filters.ts b/x-pack/legacy/plugins/uptime/public/state/reducers/overview_filters.ts index b219421f4f4dc1..0b67d8b0e7689e 100644 --- a/x-pack/legacy/plugins/uptime/public/state/reducers/overview_filters.ts +++ b/x-pack/legacy/plugins/uptime/public/state/reducers/overview_filters.ts @@ -49,6 +49,7 @@ export function overviewFiltersReducer( return { ...state, errors: [...state.errors, action.payload], + loading: false, }; default: return state; diff --git a/x-pack/legacy/plugins/uptime/public/uptime_app.tsx b/x-pack/legacy/plugins/uptime/public/uptime_app.tsx index 427870797a2064..1fcb625dad2668 100644 --- a/x-pack/legacy/plugins/uptime/public/uptime_app.tsx +++ b/x-pack/legacy/plugins/uptime/public/uptime_app.tsx @@ -23,6 +23,7 @@ import { CommonlyUsedRange } from './components/functional/uptime_date_picker'; import { store } from './state'; import { setBasePath } from './state/actions'; import { PageRouter } from './routes'; +import { apiService } from './state/api/utils'; export interface UptimeAppColors { danger: string; @@ -83,6 +84,8 @@ const Application = (props: UptimeAppProps) => { ); }, [canSave, renderGlobalHelpControls, setBadge]); + apiService.http = core.http; + // @ts-ignore store.dispatch(setBasePath(basePath)); diff --git a/x-pack/plugins/uptime/server/rest_api/index_pattern/get_index_pattern.ts b/x-pack/plugins/uptime/server/rest_api/index_pattern/get_index_pattern.ts index cc65749153c1d8..806d6e789a8909 100644 --- a/x-pack/plugins/uptime/server/rest_api/index_pattern/get_index_pattern.ts +++ b/x-pack/plugins/uptime/server/rest_api/index_pattern/get_index_pattern.ts @@ -6,10 +6,11 @@ import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; export const createGetIndexPatternRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/index_pattern', + path: API_URLS.INDEX_PATTERN, validate: false, options: { tags: ['access:uptime'], diff --git a/x-pack/plugins/uptime/server/rest_api/monitors/monitor_locations.ts b/x-pack/plugins/uptime/server/rest_api/monitors/monitor_locations.ts index f8c7666f53f7d6..131b3cbe2ab449 100644 --- a/x-pack/plugins/uptime/server/rest_api/monitors/monitor_locations.ts +++ b/x-pack/plugins/uptime/server/rest_api/monitors/monitor_locations.ts @@ -7,10 +7,11 @@ import { schema } from '@kbn/config-schema'; import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; export const createGetMonitorLocationsRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/monitor/locations', + path: API_URLS.MONITOR_LOCATIONS, validate: { query: schema.object({ monitorId: schema.string(), diff --git a/x-pack/plugins/uptime/server/rest_api/monitors/monitors_details.ts b/x-pack/plugins/uptime/server/rest_api/monitors/monitors_details.ts index ca88dd965c1ad5..66e952813eb3ea 100644 --- a/x-pack/plugins/uptime/server/rest_api/monitors/monitors_details.ts +++ b/x-pack/plugins/uptime/server/rest_api/monitors/monitors_details.ts @@ -7,10 +7,11 @@ import { schema } from '@kbn/config-schema'; import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; export const createGetMonitorDetailsRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/monitor/details', + path: API_URLS.MONITOR_DETAILS, validate: { query: schema.object({ monitorId: schema.string(), diff --git a/x-pack/plugins/uptime/server/rest_api/monitors/monitors_durations.ts b/x-pack/plugins/uptime/server/rest_api/monitors/monitors_durations.ts index 63e74175609ade..98c998b82406a5 100644 --- a/x-pack/plugins/uptime/server/rest_api/monitors/monitors_durations.ts +++ b/x-pack/plugins/uptime/server/rest_api/monitors/monitors_durations.ts @@ -7,10 +7,13 @@ import { schema } from '@kbn/config-schema'; import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; export const createGetMonitorDurationRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', path: '/api/uptime/monitor/duration', + path: API_URLS.MONITOR_DURATION, + validate: { query: schema.object({ monitorId: schema.string(), diff --git a/x-pack/plugins/uptime/server/rest_api/monitors/status.ts b/x-pack/plugins/uptime/server/rest_api/monitors/status.ts index 8dac50c9f5905d..08cbc2d70e515a 100644 --- a/x-pack/plugins/uptime/server/rest_api/monitors/status.ts +++ b/x-pack/plugins/uptime/server/rest_api/monitors/status.ts @@ -7,10 +7,12 @@ import { schema } from '@kbn/config-schema'; import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; export const createGetMonitorRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/monitor/selected', + path: API_URLS.MONITOR_SELECTED, + validate: { query: schema.object({ monitorId: schema.string(), @@ -32,7 +34,8 @@ export const createGetMonitorRoute: UMRestApiRouteFactory = (libs: UMServerLibs) export const createGetStatusBarRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/monitor/status', + path: API_URLS.MONITOR_STATUS, + validate: { query: schema.object({ monitorId: schema.string(), diff --git a/x-pack/plugins/uptime/server/rest_api/overview_filters/get_overview_filters.ts b/x-pack/plugins/uptime/server/rest_api/overview_filters/get_overview_filters.ts index 02e54cb4418382..5525771539c639 100644 --- a/x-pack/plugins/uptime/server/rest_api/overview_filters/get_overview_filters.ts +++ b/x-pack/plugins/uptime/server/rest_api/overview_filters/get_overview_filters.ts @@ -8,6 +8,7 @@ import { schema } from '@kbn/config-schema'; import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; import { objectValuesToArrays } from '../../lib/helper'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; const arrayOrStringType = schema.maybe( schema.oneOf([schema.string(), schema.arrayOf(schema.string())]) @@ -15,7 +16,7 @@ const arrayOrStringType = schema.maybe( export const createGetOverviewFilters: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/filters', + path: API_URLS.FILTERS, validate: { query: schema.object({ dateRangeStart: schema.string(), diff --git a/x-pack/plugins/uptime/server/rest_api/pings/get_all.ts b/x-pack/plugins/uptime/server/rest_api/pings/get_all.ts index 21168edfc97445..e301a2cbf9af9e 100644 --- a/x-pack/plugins/uptime/server/rest_api/pings/get_all.ts +++ b/x-pack/plugins/uptime/server/rest_api/pings/get_all.ts @@ -7,10 +7,11 @@ import { schema } from '@kbn/config-schema'; import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; export const createGetAllRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/pings', + path: API_URLS.PINGS, validate: { query: schema.object({ dateRangeStart: schema.string(), diff --git a/x-pack/plugins/uptime/server/rest_api/pings/get_ping_histogram.ts b/x-pack/plugins/uptime/server/rest_api/pings/get_ping_histogram.ts index 93ba4490fa31f6..dfaabcdf93a063 100644 --- a/x-pack/plugins/uptime/server/rest_api/pings/get_ping_histogram.ts +++ b/x-pack/plugins/uptime/server/rest_api/pings/get_ping_histogram.ts @@ -7,10 +7,11 @@ import { schema } from '@kbn/config-schema'; import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; export const createGetPingHistogramRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/ping/histogram', + path: API_URLS.PING_HISTOGRAM, validate: { query: schema.object({ dateStart: schema.string(), diff --git a/x-pack/plugins/uptime/server/rest_api/pings/get_pings.ts b/x-pack/plugins/uptime/server/rest_api/pings/get_pings.ts index e57951c98b6fce..458107dd87a777 100644 --- a/x-pack/plugins/uptime/server/rest_api/pings/get_pings.ts +++ b/x-pack/plugins/uptime/server/rest_api/pings/get_pings.ts @@ -7,10 +7,11 @@ import { schema } from '@kbn/config-schema'; import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; export const createGetPingsRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/pings', + path: API_URLS.PINGS, validate: { query: schema.object({ dateRangeStart: schema.string(), diff --git a/x-pack/plugins/uptime/server/rest_api/snapshot/get_snapshot_count.ts b/x-pack/plugins/uptime/server/rest_api/snapshot/get_snapshot_count.ts index c51806e3233071..697c49dc8300b1 100644 --- a/x-pack/plugins/uptime/server/rest_api/snapshot/get_snapshot_count.ts +++ b/x-pack/plugins/uptime/server/rest_api/snapshot/get_snapshot_count.ts @@ -7,10 +7,11 @@ import { schema } from '@kbn/config-schema'; import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; export const createGetSnapshotCount: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/snapshot/count', + path: API_URLS.SNAPSHOT_COUNT, validate: { query: schema.object({ dateRangeStart: schema.string(), From b1077a54ab64308b173504eb08b73c20b348fd90 Mon Sep 17 00:00:00 2001 From: shahzad Date: Wed, 11 Mar 2020 11:41:25 +0100 Subject: [PATCH 2/8] unused import --- .../plugins/uptime/public/state/api/__tests__/snapshot.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts index fe99f4a656b69c..2a7d50e942bca5 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts @@ -7,7 +7,6 @@ import { fetchSnapshotCount } from '../snapshot'; import { apiService } from '../utils'; import { HttpFetchError } from '../../../../../../../../src/core/public/http/http_fetch_error'; -import { message } from 'fp-ts/lib/Exception'; describe('snapshot API', () => { let fetchMock: jest.SpyInstance>>; From 5d31f8ed3dbb540b53f1b192e13efd7d05626765 Mon Sep 17 00:00:00 2001 From: shahzad Date: Fri, 13 Mar 2020 20:27:43 +0100 Subject: [PATCH 3/8] fix type --- .../plugins/uptime/public/state/api/utils.ts | 16 ++++++++++------ .../rest_api/monitors/monitors_durations.ts | 1 - 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/x-pack/legacy/plugins/uptime/public/state/api/utils.ts b/x-pack/legacy/plugins/uptime/public/state/api/utils.ts index 5ab17ee17c67ce..fc0515df54404f 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/utils.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/utils.ts @@ -8,15 +8,19 @@ import { HttpFetchQuery, HttpSetup } from '../../../../../../../target/types/cor class ApiService { private static instance: ApiService; - public http: HttpSetup; + private _http!: HttpSetup; + + public get http() { + return this._http; + } public set http(httpSetup: HttpSetup) { - this.http = httpSetup; + this._http = httpSetup; } private constructor() {} - static getInstance(): ActionsBus { + static getInstance(): ApiService { if (!ApiService.instance) { ApiService.instance = new ApiService(); } @@ -25,7 +29,7 @@ class ApiService { } public async get(apiUrl: string, params: HttpFetchQuery) { - const response = await this.http!.get(apiUrl, { query: params }); + const response = await this._http!.get(apiUrl, { query: params }); if (response instanceof Error) { throw response; } @@ -33,7 +37,7 @@ class ApiService { } public async post(apiUrl: string, data: any) { - const response = await this.http!.post(apiUrl, { + const response = await this._http!.post(apiUrl, { method: 'POST', body: JSON.stringify(data), }); @@ -44,7 +48,7 @@ class ApiService { } public async delete(apiUrl: string) { - const response = await this.http!.delete(apiUrl); + const response = await this._http!.delete(apiUrl); if (response instanceof Error) { throw response; } diff --git a/x-pack/plugins/uptime/server/rest_api/monitors/monitors_durations.ts b/x-pack/plugins/uptime/server/rest_api/monitors/monitors_durations.ts index 98c998b82406a5..f4a4cadc999764 100644 --- a/x-pack/plugins/uptime/server/rest_api/monitors/monitors_durations.ts +++ b/x-pack/plugins/uptime/server/rest_api/monitors/monitors_durations.ts @@ -11,7 +11,6 @@ import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/ export const createGetMonitorDurationRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: '/api/uptime/monitor/duration', path: API_URLS.MONITOR_DURATION, validate: { From 6ef0c5c8a5d4e029dd1948ba0a0f48ebd24fc2c7 Mon Sep 17 00:00:00 2001 From: shahzad Date: Fri, 13 Mar 2020 21:36:24 +0100 Subject: [PATCH 4/8] update type --- .../uptime/public/state/api/__tests__/snapshot.test.ts | 8 ++++---- x-pack/legacy/plugins/uptime/public/state/api/utils.ts | 2 +- .../legacy/plugins/uptime/public/state/effects/monitor.ts | 8 ++------ 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts index 2a7d50e942bca5..4788578b36b5c6 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts @@ -9,13 +9,13 @@ import { apiService } from '../utils'; import { HttpFetchError } from '../../../../../../../../src/core/public/http/http_fetch_error'; describe('snapshot API', () => { - let fetchMock: jest.SpyInstance>>; - let mockResponse: Partial; + let fetchMock: jest.SpyInstance>; + let mockResponse: Partial; beforeEach(() => { apiService.http = { get: jest.fn(), - }; + } as any; fetchMock = jest.spyOn(apiService.http, 'get'); mockResponse = { up: 3, down: 12, total: 15 }; }); @@ -63,7 +63,7 @@ describe('snapshot API', () => { }); it('throws an error when response is not ok', async () => { - mockResponse = new HttpFetchError('There was an error fetching your data.', 'error', {}); + mockResponse = new HttpFetchError('There was an error fetching your data.', 'error', {} as any); fetchMock.mockReturnValue(mockResponse); let error: Error | undefined; try { diff --git a/x-pack/legacy/plugins/uptime/public/state/api/utils.ts b/x-pack/legacy/plugins/uptime/public/state/api/utils.ts index fc0515df54404f..27b5ed34e7094c 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/utils.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/utils.ts @@ -28,7 +28,7 @@ class ApiService { return ApiService.instance; } - public async get(apiUrl: string, params: HttpFetchQuery) { + public async get(apiUrl: string, params?: HttpFetchQuery) { const response = await this._http!.get(apiUrl, { query: params }); if (response instanceof Error) { throw response; diff --git a/x-pack/legacy/plugins/uptime/public/state/effects/monitor.ts b/x-pack/legacy/plugins/uptime/public/state/effects/monitor.ts index 1cac7424b4e5ba..8f1e49a7878b51 100644 --- a/x-pack/legacy/plugins/uptime/public/state/effects/monitor.ts +++ b/x-pack/legacy/plugins/uptime/public/state/effects/monitor.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { call, put, takeLatest, select } from 'redux-saga/effects'; +import { call, put, takeLatest } from 'redux-saga/effects'; import { Action } from 'redux-actions'; import { FETCH_MONITOR_DETAILS, @@ -15,16 +15,13 @@ import { FETCH_MONITOR_LOCATIONS_FAIL, } from '../actions/monitor'; import { fetchMonitorDetails, fetchMonitorLocations } from '../api'; -import { getBasePath } from '../selectors'; import { MonitorDetailsActionPayload } from '../actions/types'; function* monitorDetailsEffect(action: Action) { const { monitorId, dateStart, dateEnd }: MonitorDetailsActionPayload = action.payload; try { - const basePath = yield select(getBasePath); const response = yield call(fetchMonitorDetails, { monitorId, - basePath, dateStart, dateEnd, }); @@ -37,8 +34,7 @@ function* monitorDetailsEffect(action: Action) { function* monitorLocationsEffect(action: Action) { const payload = action.payload; try { - const basePath = yield select(getBasePath); - const response = yield call(fetchMonitorLocations, { basePath, ...payload }); + const response = yield call(fetchMonitorLocations, payload); yield put({ type: FETCH_MONITOR_LOCATIONS_SUCCESS, payload: response }); } catch (error) { yield put({ type: FETCH_MONITOR_LOCATIONS_FAIL, payload: error.message }); From 36117e57f430cef1c0e5524edfa6fc5907a633c4 Mon Sep 17 00:00:00 2001 From: shahzad Date: Mon, 16 Mar 2020 14:15:12 +0100 Subject: [PATCH 5/8] refactor --- .../connected/charts/snapshot_container.tsx | 16 +-- .../monitor/list_drawer_container.tsx | 10 +- .../monitor/status_bar_container.tsx | 10 +- .../monitor/status_details_container.tsx | 10 +- .../plugins/uptime/public/pages/monitor.tsx | 4 +- .../uptime/public/state/actions/monitor.ts | 113 +++--------------- .../public/state/actions/monitor_status.ts | 13 +- .../uptime/public/state/actions/snapshot.ts | 52 +------- .../__snapshots__/snapshot.test.ts.snap | 6 +- .../state/api/__tests__/snapshot.test.ts | 39 +++--- .../uptime/public/state/api/monitor.ts | 26 +--- .../uptime/public/state/api/monitor_status.ts | 3 +- .../public/state/api/overview_filters.ts | 12 +- .../uptime/public/state/api/snapshot.ts | 16 +-- .../plugins/uptime/public/state/api/types.ts | 2 +- .../plugins/uptime/public/state/api/utils.ts | 33 ++++- .../public/state/effects/fetch_effect.ts | 26 ++-- .../uptime/public/state/effects/monitor.ts | 60 ++++------ .../public/state/effects/monitor_status.ts | 68 ++++------- .../uptime/public/state/effects/snapshot.ts | 14 ++- .../uptime/public/state/kibana_service.ts | 34 ++++++ .../state/reducers/__tests__/snapshot.test.ts | 54 ++++----- .../uptime/public/state/reducers/monitor.ts | 28 ++--- .../public/state/reducers/monitor_status.ts | 24 ++-- .../uptime/public/state/reducers/snapshot.ts | 16 +-- .../uptime/public/state/selectors/index.ts | 4 +- .../plugins/uptime/public/uptime_app.tsx | 4 +- .../lib/requests/get_snapshot_counts.ts | 14 +-- 28 files changed, 284 insertions(+), 427 deletions(-) create mode 100644 x-pack/legacy/plugins/uptime/public/state/kibana_service.ts diff --git a/x-pack/legacy/plugins/uptime/public/components/connected/charts/snapshot_container.tsx b/x-pack/legacy/plugins/uptime/public/components/connected/charts/snapshot_container.tsx index 08421cb56d14cd..ac8ff13d1edce9 100644 --- a/x-pack/legacy/plugins/uptime/public/components/connected/charts/snapshot_container.tsx +++ b/x-pack/legacy/plugins/uptime/public/components/connected/charts/snapshot_container.tsx @@ -8,9 +8,10 @@ import React, { useEffect } from 'react'; import { connect } from 'react-redux'; import { useUrlParams } from '../../../hooks'; import { AppState } from '../../../state'; -import { fetchSnapshotCount } from '../../../state/actions'; +import { getSnapshotCountAction } from '../../../state/actions'; import { SnapshotComponent } from '../../functional/snapshot'; import { Snapshot as SnapshotType } from '../../../../common/runtime_types'; +import { SnapShotQueryParams } from '../../../state/api'; /** * Props expected from parent components. @@ -37,7 +38,7 @@ interface StoreProps { * for this component's life cycle */ interface DispatchProps { - loadSnapshotCount: typeof fetchSnapshotCount; + loadSnapshotCount: typeof getSnapshotCountAction; } /** @@ -57,7 +58,7 @@ export const Container: React.FC = ({ const { dateRangeStart, dateRangeEnd, statusFilter } = getUrlParams(); useEffect(() => { - loadSnapshotCount(dateRangeStart, dateRangeEnd, esKuery, statusFilter); + loadSnapshotCount({ dateRangeStart, dateRangeEnd, filters: esKuery, statusFilter }); }, [dateRangeStart, dateRangeEnd, esKuery, lastRefresh, loadSnapshotCount, statusFilter]); return ; }; @@ -81,13 +82,8 @@ const mapStateToProps = ({ * @param dispatch redux-provided action dispatcher */ const mapDispatchToProps = (dispatch: any) => ({ - loadSnapshotCount: ( - dateRangeStart: string, - dateRangeEnd: string, - filters?: string, - statusFilter?: string - ): DispatchProps => { - return dispatch(fetchSnapshotCount(dateRangeStart, dateRangeEnd, filters, statusFilter)); + loadSnapshotCount: (params: SnapShotQueryParams): DispatchProps => { + return dispatch(getSnapshotCountAction(params)); }, }); diff --git a/x-pack/legacy/plugins/uptime/public/components/connected/monitor/list_drawer_container.tsx b/x-pack/legacy/plugins/uptime/public/components/connected/monitor/list_drawer_container.tsx index 8c670b485cc566..ceeaa7026059f6 100644 --- a/x-pack/legacy/plugins/uptime/public/components/connected/monitor/list_drawer_container.tsx +++ b/x-pack/legacy/plugins/uptime/public/components/connected/monitor/list_drawer_container.tsx @@ -7,9 +7,9 @@ import React, { useEffect } from 'react'; import { connect } from 'react-redux'; import { AppState } from '../../../state'; -import { getMonitorDetails } from '../../../state/selectors'; +import { monitorDetailsSelector } from '../../../state/selectors'; import { MonitorDetailsActionPayload } from '../../../state/actions/types'; -import { fetchMonitorDetails } from '../../../state/actions/monitor'; +import { getMonitorDetailsAction } from '../../../state/actions/monitor'; import { MonitorListDrawerComponent } from '../../functional/monitor_list/monitor_list_drawer/monitor_list_drawer'; import { useUrlParams } from '../../../hooks'; import { MonitorSummary } from '../../../../common/graphql/types'; @@ -18,7 +18,7 @@ import { MonitorDetails } from '../../../../common/runtime_types/monitor'; interface ContainerProps { summary: MonitorSummary; monitorDetails: MonitorDetails; - loadMonitorDetails: typeof fetchMonitorDetails; + loadMonitorDetails: typeof getMonitorDetailsAction; } const Container: React.FC = ({ summary, loadMonitorDetails, monitorDetails }) => { @@ -38,12 +38,12 @@ const Container: React.FC = ({ summary, loadMonitorDetails, moni }; const mapStateToProps = (state: AppState, { summary }: any) => ({ - monitorDetails: getMonitorDetails(state, summary), + monitorDetails: monitorDetailsSelector(state, summary), }); const mapDispatchToProps = (dispatch: any) => ({ loadMonitorDetails: (actionPayload: MonitorDetailsActionPayload) => - dispatch(fetchMonitorDetails(actionPayload)), + dispatch(getMonitorDetailsAction(actionPayload)), }); export const MonitorListDrawer = connect(mapStateToProps, mapDispatchToProps)(Container); diff --git a/x-pack/legacy/plugins/uptime/public/components/connected/monitor/status_bar_container.tsx b/x-pack/legacy/plugins/uptime/public/components/connected/monitor/status_bar_container.tsx index b2b555d32a3c7f..456fa2b30bca86 100644 --- a/x-pack/legacy/plugins/uptime/public/components/connected/monitor/status_bar_container.tsx +++ b/x-pack/legacy/plugins/uptime/public/components/connected/monitor/status_bar_container.tsx @@ -8,9 +8,9 @@ import React, { useContext, useEffect } from 'react'; import { connect } from 'react-redux'; import { Dispatch } from 'redux'; import { AppState } from '../../../state'; -import { selectMonitorLocations, selectMonitorStatus } from '../../../state/selectors'; +import { monitorLocationsSelector, selectMonitorStatus } from '../../../state/selectors'; import { MonitorStatusBarComponent } from '../../functional/monitor_status_details/monitor_status_bar'; -import { getMonitorStatus, getSelectedMonitor } from '../../../state/actions'; +import { getMonitorStatusAction, getSelectedMonitorAction } from '../../../state/actions'; import { useUrlParams } from '../../../hooks'; import { Ping } from '../../../../common/graphql/types'; import { MonitorLocations } from '../../../../common/runtime_types/monitor'; @@ -57,20 +57,20 @@ const Container: React.FC = ({ const mapStateToProps = (state: AppState, ownProps: OwnProps) => ({ monitorStatus: selectMonitorStatus(state), - monitorLocations: selectMonitorLocations(state, ownProps.monitorId), + monitorLocations: monitorLocationsSelector(state, ownProps.monitorId), }); const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => ({ loadMonitorStatus: (dateStart: string, dateEnd: string, monitorId: string) => { dispatch( - getMonitorStatus({ + getMonitorStatusAction({ monitorId, dateStart, dateEnd, }) ); dispatch( - getSelectedMonitor({ + getSelectedMonitorAction({ monitorId, }) ); diff --git a/x-pack/legacy/plugins/uptime/public/components/connected/monitor/status_details_container.tsx b/x-pack/legacy/plugins/uptime/public/components/connected/monitor/status_details_container.tsx index 6929e3bd64c4d0..3ced251dfab8c6 100644 --- a/x-pack/legacy/plugins/uptime/public/components/connected/monitor/status_details_container.tsx +++ b/x-pack/legacy/plugins/uptime/public/components/connected/monitor/status_details_container.tsx @@ -9,8 +9,8 @@ import { connect } from 'react-redux'; import { Dispatch } from 'redux'; import { useUrlParams } from '../../../hooks'; import { AppState } from '../../../state'; -import { selectMonitorLocations } from '../../../state/selectors'; -import { fetchMonitorLocations, MonitorLocationsPayload } from '../../../state/actions/monitor'; +import { monitorLocationsSelector } from '../../../state/selectors'; +import { getMonitorLocationsAction, MonitorLocationsPayload } from '../../../state/actions/monitor'; import { MonitorStatusDetailsComponent } from '../../functional/monitor_status_details'; import { MonitorLocations } from '../../../../common/runtime_types'; import { UptimeRefreshContext } from '../../../contexts'; @@ -24,7 +24,7 @@ interface StoreProps { } interface DispatchProps { - loadMonitorLocations: typeof fetchMonitorLocations; + loadMonitorLocations: typeof getMonitorLocationsAction; } type Props = OwnProps & StoreProps & DispatchProps; @@ -48,12 +48,12 @@ export const Container: React.FC = ({ ); }; const mapStateToProps = (state: AppState, { monitorId }: OwnProps) => ({ - monitorLocations: selectMonitorLocations(state, monitorId), + monitorLocations: monitorLocationsSelector(state, monitorId), }); const mapDispatchToProps = (dispatch: Dispatch) => ({ loadMonitorLocations: (params: MonitorLocationsPayload) => { - dispatch(fetchMonitorLocations(params)); + dispatch(getMonitorLocationsAction(params)); }, }); diff --git a/x-pack/legacy/plugins/uptime/public/pages/monitor.tsx b/x-pack/legacy/plugins/uptime/public/pages/monitor.tsx index 18c4927af0797d..b9d29ed017a058 100644 --- a/x-pack/legacy/plugins/uptime/public/pages/monitor.tsx +++ b/x-pack/legacy/plugins/uptime/public/pages/monitor.tsx @@ -17,7 +17,7 @@ import { MonitorStatusDetails } from '../components/connected'; import { Ping } from '../../common/graphql/types'; import { AppState } from '../state'; import { selectSelectedMonitor } from '../state/selectors'; -import { getSelectedMonitor } from '../state/actions'; +import { getSelectedMonitorAction } from '../state/actions'; import { PageHeader } from './page_header'; interface StateProps { @@ -102,7 +102,7 @@ const mapDispatchToProps: MapDispatchToPropsFunction = (dispa return { dispatchGetMonitorStatus: (monitorId: string) => { dispatch( - getSelectedMonitor({ + getSelectedMonitorAction({ monitorId, }) ); diff --git a/x-pack/legacy/plugins/uptime/public/state/actions/monitor.ts b/x-pack/legacy/plugins/uptime/public/state/actions/monitor.ts index cf4525a08e43cd..30ea8e71265e04 100644 --- a/x-pack/legacy/plugins/uptime/public/state/actions/monitor.ts +++ b/x-pack/legacy/plugins/uptime/public/state/actions/monitor.ts @@ -4,108 +4,33 @@ * you may not use this file except in compliance with the Elastic License. */ +import { createAction } from 'redux-actions'; import { MonitorDetailsActionPayload } from './types'; import { MonitorError } from '../../../common/runtime_types'; import { MonitorLocations } from '../../../common/runtime_types'; import { QueryParams } from './types'; -export const FETCH_MONITOR_DETAILS = 'FETCH_MONITOR_DETAILS'; -export const FETCH_MONITOR_DETAILS_SUCCESS = 'FETCH_MONITOR_DETAILS_SUCCESS'; -export const FETCH_MONITOR_DETAILS_FAIL = 'FETCH_MONITOR_DETAILS_FAIL'; - -export const FETCH_MONITOR_LOCATIONS = 'FETCH_MONITOR_LOCATIONS'; -export const FETCH_MONITOR_LOCATIONS_SUCCESS = 'FETCH_MONITOR_LOCATIONS_SUCCESS'; -export const FETCH_MONITOR_LOCATIONS_FAIL = 'FETCH_MONITOR_LOCATIONS_FAIL'; - -export interface MonitorDetailsState { - monitorId: string; - error: MonitorError; -} - -interface GetMonitorDetailsAction { - type: typeof FETCH_MONITOR_DETAILS; - payload: MonitorDetailsActionPayload; -} - -interface GetMonitorDetailsSuccessAction { - type: typeof FETCH_MONITOR_DETAILS_SUCCESS; - payload: MonitorDetailsState; -} - -interface GetMonitorDetailsFailAction { - type: typeof FETCH_MONITOR_DETAILS_FAIL; - payload: any; -} - export interface MonitorLocationsPayload extends QueryParams { monitorId: string; } -interface GetMonitorLocationsAction { - type: typeof FETCH_MONITOR_LOCATIONS; - payload: MonitorLocationsPayload; -} - -interface GetMonitorLocationsSuccessAction { - type: typeof FETCH_MONITOR_LOCATIONS_SUCCESS; - payload: MonitorLocations; -} - -interface GetMonitorLocationsFailAction { - type: typeof FETCH_MONITOR_LOCATIONS_FAIL; - payload: any; -} - -export function fetchMonitorDetails(payload: MonitorDetailsActionPayload): GetMonitorDetailsAction { - return { - type: FETCH_MONITOR_DETAILS, - payload, - }; -} - -export function fetchMonitorDetailsSuccess( - monitorDetailsState: MonitorDetailsState -): GetMonitorDetailsSuccessAction { - return { - type: FETCH_MONITOR_DETAILS_SUCCESS, - payload: monitorDetailsState, - }; -} - -export function fetchMonitorDetailsFail(error: any): GetMonitorDetailsFailAction { - return { - type: FETCH_MONITOR_DETAILS_FAIL, - payload: error, - }; -} - -export function fetchMonitorLocations(payload: MonitorLocationsPayload): GetMonitorLocationsAction { - return { - type: FETCH_MONITOR_LOCATIONS, - payload, - }; -} - -export function fetchMonitorLocationsSuccess( - monitorLocationsState: MonitorLocations -): GetMonitorLocationsSuccessAction { - return { - type: FETCH_MONITOR_LOCATIONS_SUCCESS, - payload: monitorLocationsState, - }; -} - -export function fetchMonitorLocationsFail(error: any): GetMonitorLocationsFailAction { - return { - type: FETCH_MONITOR_LOCATIONS_FAIL, - payload: error, - }; +export interface MonitorDetailsState { + monitorId: string; + error: MonitorError; } -export type MonitorActionTypes = - | GetMonitorDetailsAction - | GetMonitorDetailsSuccessAction - | GetMonitorDetailsFailAction - | GetMonitorLocationsAction - | GetMonitorLocationsSuccessAction - | GetMonitorLocationsFailAction; +export const getMonitorDetailsAction = createAction( + 'GET_MONITOR_DETAILS' +); +export const getMonitorDetailsActionSuccess = createAction( + 'GET_MONITOR_DETAILS_SUCCESS' +); +export const getMonitorDetailsActionFail = createAction('GET_MONITOR_DETAILS_FAIL'); + +export const getMonitorLocationsAction = createAction( + 'GET_MONITOR_LOCATIONS' +); +export const getMonitorLocationsActionSuccess = createAction( + 'GET_MONITOR_LOCATIONS_SUCCESS' +); +export const getMonitorLocationsActionFail = createAction('GET_MONITOR_LOCATIONS_FAIL'); diff --git a/x-pack/legacy/plugins/uptime/public/state/actions/monitor_status.ts b/x-pack/legacy/plugins/uptime/public/state/actions/monitor_status.ts index db103f6cb780e1..7917628abf7dae 100644 --- a/x-pack/legacy/plugins/uptime/public/state/actions/monitor_status.ts +++ b/x-pack/legacy/plugins/uptime/public/state/actions/monitor_status.ts @@ -5,11 +5,12 @@ */ import { createAction } from 'redux-actions'; import { QueryParams } from './types'; +import { Ping } from '../../../common/graphql/types'; -export const getSelectedMonitor = createAction<{ monitorId: string }>('GET_SELECTED_MONITOR'); -export const getSelectedMonitorSuccess = createAction('GET_SELECTED_MONITOR_SUCCESS'); -export const getSelectedMonitorFail = createAction('GET_SELECTED_MONITOR_FAIL'); +export const getSelectedMonitorAction = createAction<{ monitorId: string }>('GET_SELECTED_MONITOR'); +export const getSelectedMonitorActionSuccess = createAction('GET_SELECTED_MONITOR_SUCCESS'); +export const getSelectedMonitorActionFail = createAction('GET_SELECTED_MONITOR_FAIL'); -export const getMonitorStatus = createAction('GET_MONITOR_STATUS'); -export const getMonitorStatusSuccess = createAction('GET_MONITOR_STATUS_SUCCESS'); -export const getMonitorStatusFail = createAction('GET_MONITOR_STATUS_FAIL'); +export const getMonitorStatusAction = createAction('GET_MONITOR_STATUS'); +export const getMonitorStatusActionSuccess = createAction('GET_MONITOR_STATUS_SUCCESS'); +export const getMonitorStatusActionFail = createAction('GET_MONITOR_STATUS_FAIL'); diff --git a/x-pack/legacy/plugins/uptime/public/state/actions/snapshot.ts b/x-pack/legacy/plugins/uptime/public/state/actions/snapshot.ts index 57d2b4ce38204f..e819a553e61f5a 100644 --- a/x-pack/legacy/plugins/uptime/public/state/actions/snapshot.ts +++ b/x-pack/legacy/plugins/uptime/public/state/actions/snapshot.ts @@ -4,12 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ +import { createAction } from 'redux-actions'; import { Snapshot } from '../../../common/runtime_types'; -export const FETCH_SNAPSHOT_COUNT = 'FETCH_SNAPSHOT_COUNT'; -export const FETCH_SNAPSHOT_COUNT_FAIL = 'FETCH_SNAPSHOT_COUNT_FAIL'; -export const FETCH_SNAPSHOT_COUNT_SUCCESS = 'FETCH_SNAPSHOT_COUNT_SUCCESS'; - export interface GetSnapshotPayload { dateRangeStart: string; dateRangeEnd: string; @@ -17,47 +14,6 @@ export interface GetSnapshotPayload { statusFilter?: string; } -interface GetSnapshotCountFetchAction { - type: typeof FETCH_SNAPSHOT_COUNT; - payload: GetSnapshotPayload; -} - -interface GetSnapshotCountSuccessAction { - type: typeof FETCH_SNAPSHOT_COUNT_SUCCESS; - payload: Snapshot; -} - -interface GetSnapshotCountFailAction { - type: typeof FETCH_SNAPSHOT_COUNT_FAIL; - payload: Error; -} - -export type SnapshotActionTypes = - | GetSnapshotCountFetchAction - | GetSnapshotCountSuccessAction - | GetSnapshotCountFailAction; - -export const fetchSnapshotCount = ( - dateRangeStart: string, - dateRangeEnd: string, - filters?: string, - statusFilter?: string -): GetSnapshotCountFetchAction => ({ - type: FETCH_SNAPSHOT_COUNT, - payload: { - dateRangeStart, - dateRangeEnd, - filters, - statusFilter, - }, -}); - -export const fetchSnapshotCountFail = (error: Error): GetSnapshotCountFailAction => ({ - type: FETCH_SNAPSHOT_COUNT_FAIL, - payload: error, -}); - -export const fetchSnapshotCountSuccess = (snapshot: Snapshot) => ({ - type: FETCH_SNAPSHOT_COUNT_SUCCESS, - payload: snapshot, -}); +export const getSnapshotCountAction = createAction('GET_SNAPSHOT_COUNT'); +export const getSnapshotCountActionSuccess = createAction('GET_SNAPSHOT_COUNT_SUCCESS'); +export const getSnapshotCountActionFail = createAction('GET_SNAPSHOT_COUNT_FAIL'); diff --git a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/__snapshots__/snapshot.test.ts.snap b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/__snapshots__/snapshot.test.ts.snap index 575355df79227f..1cd2aae4465198 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/__snapshots__/snapshot.test.ts.snap +++ b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/__snapshots__/snapshot.test.ts.snap @@ -1,3 +1,7 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`snapshot API throws when server response doesn't correspond to expected type 1`] = `[Error: \`getSnapshotCount\` response did not correspond to expected type]`; +exports[`snapshot API throws when server response doesn't correspond to expected type 1`] = ` +Object { + "foo": "bar", +} +`; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts index 4788578b36b5c6..66b376c3ac36f4 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/snapshot.test.ts @@ -27,7 +27,6 @@ describe('snapshot API', () => { it('calls url with expected params and returns response body on 200', async () => { fetchMock.mockReturnValue(new Promise(r => r(mockResponse))); const resp = await fetchSnapshotCount({ - basePath: '', dateRangeStart: 'now-15m', dateRangeEnd: 'now', filters: 'monitor.id:"auto-http-0X21EE76EAC459873F"', @@ -47,34 +46,24 @@ describe('snapshot API', () => { it(`throws when server response doesn't correspond to expected type`, async () => { mockResponse = { foo: 'bar' }; fetchMock.mockReturnValue(new Promise(r => r(mockResponse))); - let error: Error | undefined; - try { - await fetchSnapshotCount({ - basePath: '', - dateRangeStart: 'now-15m', - dateRangeEnd: 'now', - filters: 'monitor.id: baz', - statusFilter: 'up', - }); - } catch (e) { - error = e; - } - expect(error).toMatchSnapshot(); + const result = await fetchSnapshotCount({ + dateRangeStart: 'now-15m', + dateRangeEnd: 'now', + filters: 'monitor.id: baz', + statusFilter: 'up', + }); + + expect(result).toMatchSnapshot(); }); it('throws an error when response is not ok', async () => { mockResponse = new HttpFetchError('There was an error fetching your data.', 'error', {} as any); fetchMock.mockReturnValue(mockResponse); - let error: Error | undefined; - try { - await fetchSnapshotCount({ - basePath: '', - dateRangeStart: 'now-15m', - dateRangeEnd: 'now', - }); - } catch (e) { - error = e; - } - expect(error).toEqual(new Error('There was an error fetching your data.')); + const result = await fetchSnapshotCount({ + dateRangeStart: 'now-15m', + dateRangeEnd: 'now', + }); + + expect(result).toEqual(new Error('There was an error fetching your data.')); }); }); diff --git a/x-pack/legacy/plugins/uptime/public/state/api/monitor.ts b/x-pack/legacy/plugins/uptime/public/state/api/monitor.ts index 209d2e5e270204..b36eccca98da92 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/monitor.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/monitor.ts @@ -4,14 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { PathReporter } from 'io-ts/lib/PathReporter'; import { BaseParams } from './types'; -import { - MonitorDetailsType, - MonitorDetails, - MonitorLocations, - MonitorLocationsType, -} from '../../../common/runtime_types'; +import { MonitorDetailsType, MonitorLocationsType } from '../../../common/runtime_types'; import { QueryParams } from '../actions/types'; import { apiService } from './utils'; import { API_URLS } from '../../../common/constants/rest_api'; @@ -26,32 +20,22 @@ export const fetchMonitorDetails = async ({ monitorId, dateStart, dateEnd, -}: MonitorQueryParams): Promise => { +}: MonitorQueryParams) => { const params = { monitorId, dateStart, dateEnd, }; - const response = await apiService.get(API_URLS.MONITOR_DETAILS, params); - - PathReporter.report(MonitorDetailsType.decode(response)); - return response; + return await apiService.get(API_URLS.MONITOR_DETAILS, params, MonitorDetailsType); }; type ApiParams = QueryParams & ApiRequest; -export const fetchMonitorLocations = async ({ - monitorId, - dateStart, - dateEnd, -}: ApiParams): Promise => { +export const fetchMonitorLocations = async ({ monitorId, dateStart, dateEnd }: ApiParams) => { const params = { dateStart, dateEnd, monitorId, }; - const response = await apiService.get(API_URLS.MONITOR_LOCATIONS, params); - - PathReporter.report(MonitorLocationsType.decode(response)); - return response; + return await apiService.get(API_URLS.MONITOR_LOCATIONS, params, MonitorLocationsType); }; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/monitor_status.ts b/x-pack/legacy/plugins/uptime/public/state/api/monitor_status.ts index d78067c7c18ea7..0f7608ba57ea7f 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/monitor_status.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/monitor_status.ts @@ -10,7 +10,6 @@ import { apiService } from './utils'; import { API_URLS } from '../../../common/constants/rest_api'; export interface APIParams { - basePath: string; monitorId: string; } @@ -26,7 +25,7 @@ export const fetchMonitorStatus = async ({ monitorId, dateStart, dateEnd, -}: QueryParams & APIParams): Promise => { +}: QueryParams): Promise => { const queryParams = { monitorId, dateStart, diff --git a/x-pack/legacy/plugins/uptime/public/state/api/overview_filters.ts b/x-pack/legacy/plugins/uptime/public/state/api/overview_filters.ts index 8eeca80c50f14e..9943bc27f11f02 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/overview_filters.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/overview_filters.ts @@ -4,8 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { PathReporter } from 'io-ts/lib/PathReporter'; -import { isRight } from 'fp-ts/lib/Either'; import { GetOverviewFiltersPayload } from '../actions/overview_filters'; import { OverviewFiltersType } from '../../../common/runtime_types'; import { apiService } from './utils'; @@ -30,13 +28,5 @@ export const fetchOverviewFilters = async ({ search, }; - const responseData = await apiService.get(API_URLS.FILTERS, queryParams); - - const decoded = OverviewFiltersType.decode(responseData); - - PathReporter.report(decoded); - if (isRight(decoded)) { - return decoded.right; - } - throw new Error('`getOverviewFilters` response did not correspond to expected type'); + return await apiService.get(API_URLS.FILTERS, queryParams, OverviewFiltersType); }; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/snapshot.ts b/x-pack/legacy/plugins/uptime/public/state/api/snapshot.ts index 048cf264a93b12..e663d0241d6886 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/snapshot.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/snapshot.ts @@ -4,14 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { isRight } from 'fp-ts/lib/Either'; -import { PathReporter } from 'io-ts/lib/PathReporter'; import { SnapshotType, Snapshot } from '../../../common/runtime_types'; import { apiService } from './utils'; import { API_URLS } from '../../../common/constants/rest_api'; -interface ApiRequest { - basePath: string; +export interface SnapShotQueryParams { dateRangeStart: string; dateRangeEnd: string; filters?: string; @@ -23,7 +20,7 @@ export const fetchSnapshotCount = async ({ dateRangeEnd, filters, statusFilter, -}: ApiRequest): Promise => { +}: SnapShotQueryParams): Promise => { const queryParams = { dateRangeStart, dateRangeEnd, @@ -31,12 +28,5 @@ export const fetchSnapshotCount = async ({ ...(statusFilter && { statusFilter }), }; - const responseData = await apiService.get(API_URLS.SNAPSHOT_COUNT, queryParams); - - const decoded = SnapshotType.decode(responseData); - PathReporter.report(decoded); - if (isRight(decoded)) { - return decoded.right; - } - throw new Error('`getSnapshotCount` response did not correspond to expected type'); + return await apiService.get(API_URLS.SNAPSHOT_COUNT, queryParams, SnapshotType); }; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/types.ts b/x-pack/legacy/plugins/uptime/public/state/api/types.ts index e54275d30d51e4..4232751cbc0324 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/types.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/types.ts @@ -13,4 +13,4 @@ export interface BaseParams { monitorId?: string; } -export type APIFn = (params: { basePath: string } & P) => Promise; +export type APIFn = (params: P) => Promise; diff --git a/x-pack/legacy/plugins/uptime/public/state/api/utils.ts b/x-pack/legacy/plugins/uptime/public/state/api/utils.ts index 27b5ed34e7094c..e67efa8570c110 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/utils.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/utils.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import { PathReporter } from 'io-ts/lib/PathReporter'; +import { isRight } from 'fp-ts/lib/Either'; import { HttpFetchQuery, HttpSetup } from '../../../../../../../target/types/core/public'; class ApiService { @@ -28,21 +30,40 @@ class ApiService { return ApiService.instance; } - public async get(apiUrl: string, params?: HttpFetchQuery) { + public async get(apiUrl: string, params?: HttpFetchQuery, decodeType?: any) { const response = await this._http!.get(apiUrl, { query: params }); - if (response instanceof Error) { - throw response; + + if (decodeType) { + const decoded = decodeType.decode(response); + if (isRight(decoded)) { + return decoded.right; + } else { + // eslint-disable-next-line no-console + console.error( + `API ${apiUrl} is not returning expected response, ${PathReporter.report(decoded)}` + ); + } } + return response; } - public async post(apiUrl: string, data: any) { + public async post(apiUrl: string, data?: any, decodeType?: any) { const response = await this._http!.post(apiUrl, { method: 'POST', body: JSON.stringify(data), }); - if (response instanceof Error) { - throw response; + + if (decodeType) { + const decoded = decodeType.decode(response); + if (isRight(decoded)) { + return decoded.right; + } else { + // eslint-disable-next-line no-console + console.warn( + `API ${apiUrl} is not returning expected response, ${PathReporter.report(decoded)}` + ); + } } return response; } diff --git a/x-pack/legacy/plugins/uptime/public/state/effects/fetch_effect.ts b/x-pack/legacy/plugins/uptime/public/state/effects/fetch_effect.ts index 4ca61c70dfa828..d1d7626b2eab39 100644 --- a/x-pack/legacy/plugins/uptime/public/state/effects/fetch_effect.ts +++ b/x-pack/legacy/plugins/uptime/public/state/effects/fetch_effect.ts @@ -4,9 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { call, put, select } from 'redux-saga/effects'; +import { call, put } from 'redux-saga/effects'; import { Action } from 'redux-actions'; -import { getBasePath } from '../selectors'; /** * Factory function for a fetch effect. It expects three action creators, @@ -25,22 +24,17 @@ export function fetchEffectFactory( fail: (error: Error) => Action ) { return function*(action: Action) { - try { - if (!action.payload) { - yield put(fail(new Error('Cannot fetch snapshot for undefined parameters.'))); - return; - } - const { - payload: { ...params }, - } = action; - const basePath = yield select(getBasePath); - const response = yield call(fetch, { ...params, basePath }); - yield put(success(response)); - } catch (error) { + const { + payload: { ...params }, + } = action; + const response = yield call(fetch, params); + if (response instanceof Error) { // eslint-disable-next-line no-console - console.error(error); + console.error(response); - yield put(fail(error)); + yield put(fail(response)); + } else { + yield put(success(response)); } }; } diff --git a/x-pack/legacy/plugins/uptime/public/state/effects/monitor.ts b/x-pack/legacy/plugins/uptime/public/state/effects/monitor.ts index 8f1e49a7878b51..ed21f315476d4e 100644 --- a/x-pack/legacy/plugins/uptime/public/state/effects/monitor.ts +++ b/x-pack/legacy/plugins/uptime/public/state/effects/monitor.ts @@ -4,44 +4,34 @@ * you may not use this file except in compliance with the Elastic License. */ -import { call, put, takeLatest } from 'redux-saga/effects'; -import { Action } from 'redux-actions'; +import { takeLatest } from 'redux-saga/effects'; import { - FETCH_MONITOR_DETAILS, - FETCH_MONITOR_DETAILS_SUCCESS, - FETCH_MONITOR_DETAILS_FAIL, - FETCH_MONITOR_LOCATIONS, - FETCH_MONITOR_LOCATIONS_SUCCESS, - FETCH_MONITOR_LOCATIONS_FAIL, + getMonitorDetailsAction, + getMonitorDetailsActionSuccess, + getMonitorDetailsActionFail, + getMonitorLocationsAction, + getMonitorLocationsActionSuccess, + getMonitorLocationsActionFail, } from '../actions/monitor'; import { fetchMonitorDetails, fetchMonitorLocations } from '../api'; -import { MonitorDetailsActionPayload } from '../actions/types'; - -function* monitorDetailsEffect(action: Action) { - const { monitorId, dateStart, dateEnd }: MonitorDetailsActionPayload = action.payload; - try { - const response = yield call(fetchMonitorDetails, { - monitorId, - dateStart, - dateEnd, - }); - yield put({ type: FETCH_MONITOR_DETAILS_SUCCESS, payload: response }); - } catch (error) { - yield put({ type: FETCH_MONITOR_DETAILS_FAIL, payload: error.message }); - } -} - -function* monitorLocationsEffect(action: Action) { - const payload = action.payload; - try { - const response = yield call(fetchMonitorLocations, payload); - yield put({ type: FETCH_MONITOR_LOCATIONS_SUCCESS, payload: response }); - } catch (error) { - yield put({ type: FETCH_MONITOR_LOCATIONS_FAIL, payload: error.message }); - } -} +import { fetchEffectFactory } from './fetch_effect'; export function* fetchMonitorDetailsEffect() { - yield takeLatest(FETCH_MONITOR_DETAILS, monitorDetailsEffect); - yield takeLatest(FETCH_MONITOR_LOCATIONS, monitorLocationsEffect); + yield takeLatest( + getMonitorDetailsAction, + fetchEffectFactory( + fetchMonitorDetails, + getMonitorDetailsActionSuccess, + getMonitorDetailsActionFail + ) + ); + + yield takeLatest( + getMonitorLocationsAction, + fetchEffectFactory( + fetchMonitorLocations, + getMonitorLocationsActionSuccess, + getMonitorLocationsActionFail + ) + ); } diff --git a/x-pack/legacy/plugins/uptime/public/state/effects/monitor_status.ts b/x-pack/legacy/plugins/uptime/public/state/effects/monitor_status.ts index cab32092a14cd2..1207ab20bc7113 100644 --- a/x-pack/legacy/plugins/uptime/public/state/effects/monitor_status.ts +++ b/x-pack/legacy/plugins/uptime/public/state/effects/monitor_status.ts @@ -4,50 +4,34 @@ * you may not use this file except in compliance with the Elastic License. */ -import { call, put, takeLatest, select } from 'redux-saga/effects'; -import { Action } from 'redux-actions'; +import { takeLatest } from 'redux-saga/effects'; import { - getSelectedMonitor, - getSelectedMonitorSuccess, - getSelectedMonitorFail, - getMonitorStatus, - getMonitorStatusSuccess, - getMonitorStatusFail, -} from '../actions/monitor_status'; + getSelectedMonitorAction, + getSelectedMonitorActionSuccess, + getSelectedMonitorActionFail, + getMonitorStatusAction, + getMonitorStatusActionSuccess, + getMonitorStatusActionFail, +} from '../actions'; import { fetchSelectedMonitor, fetchMonitorStatus } from '../api'; -import { getBasePath } from '../selectors'; - -function* selectedMonitorEffect(action: Action) { - const { monitorId } = action.payload; - try { - const basePath = yield select(getBasePath); - const response = yield call(fetchSelectedMonitor, { - monitorId, - basePath, - }); - yield put({ type: getSelectedMonitorSuccess, payload: response }); - } catch (error) { - yield put({ type: getSelectedMonitorFail, payload: error.message }); - } -} - -function* monitorStatusEffect(action: Action) { - const { monitorId, dateStart, dateEnd } = action.payload; - try { - const basePath = yield select(getBasePath); - const response = yield call(fetchMonitorStatus, { - monitorId, - basePath, - dateStart, - dateEnd, - }); - yield put({ type: getMonitorStatusSuccess, payload: response }); - } catch (error) { - yield put({ type: getMonitorStatusFail, payload: error.message }); - } -} +import { fetchEffectFactory } from './fetch_effect'; export function* fetchMonitorStatusEffect() { - yield takeLatest(getMonitorStatus, monitorStatusEffect); - yield takeLatest(getSelectedMonitor, selectedMonitorEffect); + yield takeLatest( + getMonitorStatusAction, + fetchEffectFactory( + fetchMonitorStatus, + getMonitorStatusActionSuccess, + getMonitorStatusActionFail + ) + ); + + yield takeLatest( + getSelectedMonitorAction, + fetchEffectFactory( + fetchSelectedMonitor, + getSelectedMonitorActionSuccess, + getSelectedMonitorActionFail + ) + ); } diff --git a/x-pack/legacy/plugins/uptime/public/state/effects/snapshot.ts b/x-pack/legacy/plugins/uptime/public/state/effects/snapshot.ts index 91df43dd9e8262..10010004d47a02 100644 --- a/x-pack/legacy/plugins/uptime/public/state/effects/snapshot.ts +++ b/x-pack/legacy/plugins/uptime/public/state/effects/snapshot.ts @@ -6,16 +6,20 @@ import { takeLatest } from 'redux-saga/effects'; import { - FETCH_SNAPSHOT_COUNT, - fetchSnapshotCountFail, - fetchSnapshotCountSuccess, + getSnapshotCountAction, + getSnapshotCountActionFail, + getSnapshotCountActionSuccess, } from '../actions'; import { fetchSnapshotCount } from '../api'; import { fetchEffectFactory } from './fetch_effect'; export function* fetchSnapshotCountEffect() { yield takeLatest( - FETCH_SNAPSHOT_COUNT, - fetchEffectFactory(fetchSnapshotCount, fetchSnapshotCountSuccess, fetchSnapshotCountFail) + getSnapshotCountAction, + fetchEffectFactory( + fetchSnapshotCount, + getSnapshotCountActionSuccess, + getSnapshotCountActionFail + ) ); } diff --git a/x-pack/legacy/plugins/uptime/public/state/kibana_service.ts b/x-pack/legacy/plugins/uptime/public/state/kibana_service.ts new file mode 100644 index 00000000000000..4fd2d446daa171 --- /dev/null +++ b/x-pack/legacy/plugins/uptime/public/state/kibana_service.ts @@ -0,0 +1,34 @@ +/* + * 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 { CoreStart } from 'kibana/public'; +import { apiService } from './api/utils'; + +class KibanaService { + private static instance: KibanaService; + private _core!: CoreStart; + + public get core() { + return this._core; + } + + public set core(coreStart: CoreStart) { + this._core = coreStart; + apiService.http = this._core.http; + } + + private constructor() {} + + static getInstance(): KibanaService { + if (!KibanaService.instance) { + KibanaService.instance = new KibanaService(); + } + + return KibanaService.instance; + } +} + +export const kibanaService = KibanaService.getInstance(); diff --git a/x-pack/legacy/plugins/uptime/public/state/reducers/__tests__/snapshot.test.ts b/x-pack/legacy/plugins/uptime/public/state/reducers/__tests__/snapshot.test.ts index 95c576e0fd72e5..3650422571ce81 100644 --- a/x-pack/legacy/plugins/uptime/public/state/reducers/__tests__/snapshot.test.ts +++ b/x-pack/legacy/plugins/uptime/public/state/reducers/__tests__/snapshot.test.ts @@ -5,19 +5,20 @@ */ import { snapshotReducer } from '../snapshot'; -import { SnapshotActionTypes } from '../../actions'; +import { + getSnapshotCountAction, + getSnapshotCountActionSuccess, + getSnapshotCountActionFail, +} from '../../actions'; describe('snapshot reducer', () => { it('updates existing state', () => { - const action: SnapshotActionTypes = { - type: 'FETCH_SNAPSHOT_COUNT', - payload: { - dateRangeStart: 'now-15m', - dateRangeEnd: 'now', - filters: 'foo: bar', - statusFilter: 'up', - }, - }; + const action = getSnapshotCountAction({ + dateRangeStart: 'now-15m', + dateRangeEnd: 'now', + filters: 'foo: bar', + statusFilter: 'up', + }); expect( snapshotReducer( { @@ -31,33 +32,28 @@ describe('snapshot reducer', () => { }); it(`sets the state's status to loading during a fetch`, () => { - const action: SnapshotActionTypes = { - type: 'FETCH_SNAPSHOT_COUNT', - payload: { - dateRangeStart: 'now-15m', - dateRangeEnd: 'now', - }, - }; + const action = getSnapshotCountAction({ + dateRangeStart: 'now-15m', + dateRangeEnd: 'now', + }); expect(snapshotReducer(undefined, action)).toMatchSnapshot(); }); it('changes the count when a snapshot fetch succeeds', () => { - const action: SnapshotActionTypes = { - type: 'FETCH_SNAPSHOT_COUNT_SUCCESS', - payload: { - up: 10, - down: 15, - total: 25, - }, - }; + const action = getSnapshotCountActionSuccess({ + up: 10, + down: 15, + total: 25, + }); + expect(snapshotReducer(undefined, action)).toMatchSnapshot(); }); it('appends a current error to existing errors list', () => { - const action: SnapshotActionTypes = { - type: 'FETCH_SNAPSHOT_COUNT_FAIL', - payload: new Error(`I couldn't get your data because the server denied the request`), - }; + const action = getSnapshotCountActionFail( + new Error(`I couldn't get your data because the server denied the request`) + ); + expect(snapshotReducer(undefined, action)).toMatchSnapshot(); }); }); diff --git a/x-pack/legacy/plugins/uptime/public/state/reducers/monitor.ts b/x-pack/legacy/plugins/uptime/public/state/reducers/monitor.ts index aac8a90598d0c0..632f3a270e1a1c 100644 --- a/x-pack/legacy/plugins/uptime/public/state/reducers/monitor.ts +++ b/x-pack/legacy/plugins/uptime/public/state/reducers/monitor.ts @@ -4,15 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ +import { Action } from 'redux-actions'; import { - MonitorActionTypes, MonitorDetailsState, - FETCH_MONITOR_DETAILS, - FETCH_MONITOR_DETAILS_SUCCESS, - FETCH_MONITOR_DETAILS_FAIL, - FETCH_MONITOR_LOCATIONS, - FETCH_MONITOR_LOCATIONS_SUCCESS, - FETCH_MONITOR_LOCATIONS_FAIL, + getMonitorDetailsAction, + getMonitorLocationsAction, + getMonitorDetailsActionSuccess, + getMonitorDetailsActionFail, + getMonitorLocationsActionSuccess, + getMonitorLocationsActionFail, } from '../actions/monitor'; import { MonitorLocations } from '../../../common/runtime_types'; @@ -32,14 +32,14 @@ const initialState: MonitorState = { errors: [], }; -export function monitorReducer(state = initialState, action: MonitorActionTypes): MonitorState { +export function monitorReducer(state = initialState, action: Action): MonitorState { switch (action.type) { - case FETCH_MONITOR_DETAILS: + case String(getMonitorDetailsAction): return { ...state, loading: true, }; - case FETCH_MONITOR_DETAILS_SUCCESS: + case String(getMonitorDetailsActionSuccess): const { monitorId } = action.payload; return { ...state, @@ -49,17 +49,17 @@ export function monitorReducer(state = initialState, action: MonitorActionTypes) }, loading: false, }; - case FETCH_MONITOR_DETAILS_FAIL: + case String(getMonitorDetailsActionFail): return { ...state, errors: [...state.errors, action.payload], }; - case FETCH_MONITOR_LOCATIONS: + case String(getMonitorLocationsAction): return { ...state, loading: true, }; - case FETCH_MONITOR_LOCATIONS_SUCCESS: + case String(getMonitorLocationsActionSuccess): const monLocations = state.monitorLocationsList; monLocations.set(action.payload.monitorId, action.payload); return { @@ -67,7 +67,7 @@ export function monitorReducer(state = initialState, action: MonitorActionTypes) monitorLocationsList: monLocations, loading: false, }; - case FETCH_MONITOR_LOCATIONS_FAIL: + case String(getMonitorLocationsActionFail): return { ...state, errors: [...state.errors, action.payload], diff --git a/x-pack/legacy/plugins/uptime/public/state/reducers/monitor_status.ts b/x-pack/legacy/plugins/uptime/public/state/reducers/monitor_status.ts index 2688a0946dd610..c2dfbd7f90ff23 100644 --- a/x-pack/legacy/plugins/uptime/public/state/reducers/monitor_status.ts +++ b/x-pack/legacy/plugins/uptime/public/state/reducers/monitor_status.ts @@ -5,12 +5,12 @@ */ import { handleActions, Action } from 'redux-actions'; import { - getSelectedMonitor, - getSelectedMonitorSuccess, - getSelectedMonitorFail, - getMonitorStatus, - getMonitorStatusSuccess, - getMonitorStatusFail, + getSelectedMonitorAction, + getSelectedMonitorActionSuccess, + getSelectedMonitorActionFail, + getMonitorStatusAction, + getMonitorStatusActionSuccess, + getMonitorStatusActionFail, } from '../actions'; import { Ping } from '../../../common/graphql/types'; import { QueryParams } from '../actions/types'; @@ -31,34 +31,34 @@ type MonitorStatusPayload = QueryParams & Ping; export const monitorStatusReducer = handleActions( { - [String(getSelectedMonitor)]: (state, action: Action) => ({ + [String(getSelectedMonitorAction)]: (state, action: Action) => ({ ...state, loading: true, }), - [String(getSelectedMonitorSuccess)]: (state, action: Action) => ({ + [String(getSelectedMonitorActionSuccess)]: (state, action: Action) => ({ ...state, loading: false, monitor: { ...action.payload } as Ping, }), - [String(getSelectedMonitorFail)]: (state, action: Action) => ({ + [String(getSelectedMonitorActionFail)]: (state, action: Action) => ({ ...state, loading: false, }), - [String(getMonitorStatus)]: (state, action: Action) => ({ + [String(getMonitorStatusAction)]: (state, action: Action) => ({ ...state, loading: true, }), - [String(getMonitorStatusSuccess)]: (state, action: Action) => ({ + [String(getMonitorStatusActionSuccess)]: (state, action: Action) => ({ ...state, loading: false, status: { ...action.payload } as Ping, }), - [String(getMonitorStatusFail)]: (state, action: Action) => ({ + [String(getMonitorStatusActionFail)]: (state, action: Action) => ({ ...state, loading: false, }), diff --git a/x-pack/legacy/plugins/uptime/public/state/reducers/snapshot.ts b/x-pack/legacy/plugins/uptime/public/state/reducers/snapshot.ts index 2155d0e3a74e3c..3ba1ef84d41a59 100644 --- a/x-pack/legacy/plugins/uptime/public/state/reducers/snapshot.ts +++ b/x-pack/legacy/plugins/uptime/public/state/reducers/snapshot.ts @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ +import { Action } from 'redux-actions'; import { Snapshot } from '../../../common/runtime_types'; import { - FETCH_SNAPSHOT_COUNT, - FETCH_SNAPSHOT_COUNT_FAIL, - FETCH_SNAPSHOT_COUNT_SUCCESS, - SnapshotActionTypes, + getSnapshotCountAction, + getSnapshotCountActionSuccess, + getSnapshotCountActionFail, } from '../actions'; export interface SnapshotState { @@ -28,20 +28,20 @@ const initialState: SnapshotState = { loading: false, }; -export function snapshotReducer(state = initialState, action: SnapshotActionTypes): SnapshotState { +export function snapshotReducer(state = initialState, action: Action): SnapshotState { switch (action.type) { - case FETCH_SNAPSHOT_COUNT: + case String(getSnapshotCountAction): return { ...state, loading: true, }; - case FETCH_SNAPSHOT_COUNT_SUCCESS: + case String(getSnapshotCountActionSuccess): return { ...state, count: action.payload, loading: false, }; - case FETCH_SNAPSHOT_COUNT_FAIL: + case String(getSnapshotCountActionFail): return { ...state, errors: [...state.errors, action.payload], diff --git a/x-pack/legacy/plugins/uptime/public/state/selectors/index.ts b/x-pack/legacy/plugins/uptime/public/state/selectors/index.ts index 0a914a14c372be..66ee752eb23956 100644 --- a/x-pack/legacy/plugins/uptime/public/state/selectors/index.ts +++ b/x-pack/legacy/plugins/uptime/public/state/selectors/index.ts @@ -13,11 +13,11 @@ export const isIntegrationsPopupOpen = ({ ui: { integrationsPopoverOpen } }: App integrationsPopoverOpen; // Monitor Selectors -export const getMonitorDetails = (state: AppState, summary: any) => { +export const monitorDetailsSelector = (state: AppState, summary: any) => { return state.monitor.monitorDetailsList[summary.monitor_id]; }; -export const selectMonitorLocations = (state: AppState, monitorId: string) => { +export const monitorLocationsSelector = (state: AppState, monitorId: string) => { return state.monitor.monitorLocationsList?.get(monitorId); }; diff --git a/x-pack/legacy/plugins/uptime/public/uptime_app.tsx b/x-pack/legacy/plugins/uptime/public/uptime_app.tsx index 1fcb625dad2668..09156db9ca7d23 100644 --- a/x-pack/legacy/plugins/uptime/public/uptime_app.tsx +++ b/x-pack/legacy/plugins/uptime/public/uptime_app.tsx @@ -23,7 +23,7 @@ import { CommonlyUsedRange } from './components/functional/uptime_date_picker'; import { store } from './state'; import { setBasePath } from './state/actions'; import { PageRouter } from './routes'; -import { apiService } from './state/api/utils'; +import { kibanaService } from './state/kibana_service'; export interface UptimeAppColors { danger: string; @@ -84,7 +84,7 @@ const Application = (props: UptimeAppProps) => { ); }, [canSave, renderGlobalHelpControls, setBadge]); - apiService.http = core.http; + kibanaService.core = core; // @ts-ignore store.dispatch(setBasePath(basePath)); diff --git a/x-pack/plugins/uptime/server/lib/requests/get_snapshot_counts.ts b/x-pack/plugins/uptime/server/lib/requests/get_snapshot_counts.ts index ca9da51cc7ba85..1783c6e91df344 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_snapshot_counts.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_snapshot_counts.ts @@ -89,7 +89,7 @@ const statusCountBody = (filters: any): any => { String id = doc["monitor.id"][0]; String idLenDelim = Integer.toHexString(id.length()) + ":" + id; String idLoc = loc == null ? idLenDelim : idLenDelim + loc; - + String status = doc["summary.down"][0] > 0 ? "d" : "u"; String timeAndStatus = doc["@timestamp"][0].toInstant().toEpochMilli().toString() + status; state.locStatus[idLoc] = timeAndStatus; @@ -111,7 +111,7 @@ const statusCountBody = (filters: any): any => { locStatus.merge(entry.getKey(), entry.getValue(), (a,b) -> a.compareTo(b) > 0 ? a : b) } } - + HashMap locTotals = new HashMap(); int total = 0; int down = 0; @@ -130,7 +130,7 @@ const statusCountBody = (filters: any): any => { String id = idLoc.substring(colonIndex + 1, idEnd); String loc = idLoc.substring(idEnd, idLoc.length()); String status = timeStatus.substring(timeStatus.length() - 1); - + // Here we increment counters for the up/down key per location // We also create a new hashmap in locTotals if we've never seen this location // before. @@ -141,7 +141,7 @@ const statusCountBody = (filters: any): any => { res.put('up', 0); res.put('down', 0); } - + if (status == 'u') { res.up++; } else { @@ -150,8 +150,8 @@ const statusCountBody = (filters: any): any => { return res; }); - - + + // We've encountered a new ID if (curId != id) { total++; @@ -171,7 +171,7 @@ const statusCountBody = (filters: any): any => { } } } - + Map result = new HashMap(); result.total = total; result.location_totals = locTotals; From 0dc7e8afedef210d68ace9264cfa8ce6b8422bfa Mon Sep 17 00:00:00 2001 From: shahzad Date: Mon, 16 Mar 2020 15:53:36 +0100 Subject: [PATCH 6/8] fix types --- .../uptime/public/state/api/index_pattern.ts | 2 +- .../uptime/public/state/api/index_status.ts | 26 +++---------------- 2 files changed, 5 insertions(+), 23 deletions(-) diff --git a/x-pack/legacy/plugins/uptime/public/state/api/index_pattern.ts b/x-pack/legacy/plugins/uptime/public/state/api/index_pattern.ts index c440b8ad758cd7..1eecbc75c5bf40 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/index_pattern.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/index_pattern.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { API_URLS } from '../../../common/constants/rest_api'; +import { API_URLS } from '../../../common/constants'; import { apiService } from './utils'; export const fetchIndexPattern = async () => { diff --git a/x-pack/legacy/plugins/uptime/public/state/api/index_status.ts b/x-pack/legacy/plugins/uptime/public/state/api/index_status.ts index 9c531b3406a7c8..b2267ff2d00c79 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/index_status.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/index_status.ts @@ -4,28 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { PathReporter } from 'io-ts/lib/PathReporter'; -import { isRight } from 'fp-ts/lib/Either'; -import { getApiPath } from '../../lib/helper'; -import { REST_API_URLS } from '../../../common/constants/rest_api'; +import { API_URLS } from '../../../common/constants'; import { StatesIndexStatus, StatesIndexStatusType } from '../../../common/runtime_types'; +import { apiService } from './utils'; -interface ApiRequest { - basePath: string; -} - -export const fetchIndexStatus = async ({ basePath }: ApiRequest): Promise => { - const url = getApiPath(REST_API_URLS.INDEX_STATUS, basePath); - - const response = await fetch(url); - if (!response.ok) { - throw new Error(response.statusText); - } - const responseData = await response.json(); - const decoded = StatesIndexStatusType.decode(responseData); - PathReporter.report(decoded); - if (isRight(decoded)) { - return decoded.right; - } - throw PathReporter.report(decoded); +export const fetchIndexStatus = async (): Promise => { + return await apiService.get(API_URLS.INDEX_STATUS, null, StatesIndexStatusType); }; From 570162bd322ddc89bf7a9a4d23673143bc4cfe5d Mon Sep 17 00:00:00 2001 From: shahzad Date: Mon, 16 Mar 2020 16:01:47 +0100 Subject: [PATCH 7/8] fix type --- x-pack/legacy/plugins/uptime/public/state/api/index_status.ts | 2 +- .../uptime/server/rest_api/index_state/get_index_status.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/x-pack/legacy/plugins/uptime/public/state/api/index_status.ts b/x-pack/legacy/plugins/uptime/public/state/api/index_status.ts index b2267ff2d00c79..0e33ab617777a1 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/index_status.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/index_status.ts @@ -9,5 +9,5 @@ import { StatesIndexStatus, StatesIndexStatusType } from '../../../common/runtim import { apiService } from './utils'; export const fetchIndexStatus = async (): Promise => { - return await apiService.get(API_URLS.INDEX_STATUS, null, StatesIndexStatusType); + return await apiService.get(API_URLS.INDEX_STATUS, undefined, StatesIndexStatusType); }; diff --git a/x-pack/plugins/uptime/server/rest_api/index_state/get_index_status.ts b/x-pack/plugins/uptime/server/rest_api/index_state/get_index_status.ts index 44799aa19c140e..d4d76c86870ee8 100644 --- a/x-pack/plugins/uptime/server/rest_api/index_state/get_index_status.ts +++ b/x-pack/plugins/uptime/server/rest_api/index_state/get_index_status.ts @@ -6,11 +6,11 @@ import { UMServerLibs } from '../../lib/lib'; import { UMRestApiRouteFactory } from '../types'; -import { REST_API_URLS } from '../../../../../legacy/plugins/uptime/common/constants/rest_api'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants'; export const createGetIndexStatusRoute: UMRestApiRouteFactory = (libs: UMServerLibs) => ({ method: 'GET', - path: REST_API_URLS.INDEX_STATUS, + path: API_URLS.INDEX_STATUS, validate: false, options: { tags: ['access:uptime'], From 6d9f6429797dda06f8aa010ca0da3c3fcafa8724 Mon Sep 17 00:00:00 2001 From: shahzad Date: Mon, 16 Mar 2020 17:17:01 +0100 Subject: [PATCH 8/8] fix type --- x-pack/test/api_integration/apis/uptime/feature_controls.ts | 4 ++-- x-pack/test/api_integration/apis/uptime/rest/doc_count.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/x-pack/test/api_integration/apis/uptime/feature_controls.ts b/x-pack/test/api_integration/apis/uptime/feature_controls.ts index 15666acab2335d..91ea1bedb061a7 100644 --- a/x-pack/test/api_integration/apis/uptime/feature_controls.ts +++ b/x-pack/test/api_integration/apis/uptime/feature_controls.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; import { PINGS_DATE_RANGE_END, PINGS_DATE_RANGE_START } from './constants'; -import { REST_API_URLS } from '../../../../legacy/plugins/uptime/common/constants'; +import { API_URLS } from '../../../../legacy/plugins/uptime/common/constants'; export default function featureControlsTests({ getService }: FtrProviderContext) { const supertest = getService('supertestWithoutAuth'); @@ -30,7 +30,7 @@ export default function featureControlsTests({ getService }: FtrProviderContext) const basePath = spaceId ? `/s/${spaceId}` : ''; return await supertest - .get(basePath + REST_API_URLS.INDEX_STATUS) + .get(basePath + API_URLS.INDEX_STATUS) .auth(username, password) .set('kbn-xsrf', 'foo') .then((response: any) => ({ error: undefined, response })) diff --git a/x-pack/test/api_integration/apis/uptime/rest/doc_count.ts b/x-pack/test/api_integration/apis/uptime/rest/doc_count.ts index 1f5322f581b39d..3f42511dd165c8 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/doc_count.ts +++ b/x-pack/test/api_integration/apis/uptime/rest/doc_count.ts @@ -5,14 +5,14 @@ */ import { FtrProviderContext } from '../../../ftr_provider_context'; import { expectFixtureEql } from '../graphql/helpers/expect_fixture_eql'; -import { REST_API_URLS } from '../../../../../legacy/plugins/uptime/common/constants'; +import { API_URLS } from '../../../../../legacy/plugins/uptime/common/constants'; export default function({ getService }: FtrProviderContext) { describe('docCount query', () => { const supertest = getService('supertest'); it(`will fetch the index's count`, async () => { - const apiResponse = await supertest.get(REST_API_URLS.INDEX_STATUS); + const apiResponse = await supertest.get(API_URLS.INDEX_STATUS); const data = apiResponse.body; expectFixtureEql(data, 'doc_count'); });