Skip to content

Commit

Permalink
[Watcher] New Platform (NP) Migration (elastic#50908)
Browse files Browse the repository at this point in the history
* First iteration of watch public -> new platform
Still need to switch to np ready version of use_request

* - Switched to using np ready request
- Some updates after API changes

* First attempt at server shim

* Rename file and re-enable react hooks linting

* Fix some public types and react hooks lint rules

* Fix types

* More ES lint react hooks fixes

* Migrated server lib -> ts. Part way done with migrating routes to NP router and TS

* Big subset of routes to TS and NP router - almost there

* Delete legacy error wrappers and moved last set of routes to TS and NP router

* Remove @ts-ignore's and update route registration to use shim with http router

* Added routes validations, fixes for hooks and fixes for types

* Fix more types and finish testing API routes

* Fix usage of feature catalogue and fix time buckets types

* Fix error message shape [skip ci]

* Split legacy from new platform dependencies server-side

* Refactor: Seperate client legacy and NP dependencies

* Add file: added types file

* Fix UISettings client type import

* Update license pre-routing factory spec

* Update variable names, use of I18nContext (use NP) and docs

* Use NP elasticsearchclient

* Simplify is_es_error_factory

* Fix types

* Improve code legibility and remove second use of `useAppContext`

* Use @kbn/config-schema (not validate: false) on routes!

* Fix watch create JSON spec

* Create threshold test working

* Unskip watch_edit.test.ts

* Unskip watch_list.test.ts

* Done re-enabling component integration tests

* TimeBuckets typo + remove unnecessary // @ts-ignore
  • Loading branch information
jloleysens committed Dec 11, 2019
1 parent 2d8bf21 commit 307c124
Show file tree
Hide file tree
Showing 255 changed files with 2,306 additions and 2,221 deletions.
7 changes: 0 additions & 7 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,13 +209,6 @@ module.exports = {
'react-hooks/rules-of-hooks': 'off',
},
},
{
files: ['x-pack/legacy/plugins/watcher/**/*.{js,ts,tsx}'],
rules: {
'react-hooks/rules-of-hooks': 'off',
'react-hooks/exhaustive-deps': 'off',
},
},

/**
* Prettier
Expand Down
22 changes: 22 additions & 0 deletions src/legacy/ui/public/time_buckets/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

declare module 'ui/time_buckets' {
export const TimeBuckets: any;
}
9 changes: 6 additions & 3 deletions src/plugins/es_ui_shared/public/request/np_ready_request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@

import { useEffect, useState, useRef } from 'react';

import { HttpServiceBase } from '../../../../../src/core/public';
import { HttpServiceBase, HttpFetchQuery } from '../../../../../src/core/public';

export interface SendRequestConfig {
path: string;
method: 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head';
query?: HttpFetchQuery;
body?: any;
}

Expand All @@ -48,10 +49,10 @@ export interface UseRequestResponse {

export const sendRequest = async (
httpClient: HttpServiceBase,
{ path, method, body }: SendRequestConfig
{ path, method, body, query }: SendRequestConfig
): Promise<SendRequestResponse> => {
try {
const response = await httpClient[method](path, { body });
const response = await httpClient[method](path, { body, query });

return {
data: response.data ? response.data : response,
Expand All @@ -70,6 +71,7 @@ export const useRequest = (
{
path,
method,
query,
body,
pollIntervalMs,
initialData,
Expand Down Expand Up @@ -112,6 +114,7 @@ export const useRequest = (
const requestBody = {
path,
method,
query,
body,
};

Expand Down
3 changes: 2 additions & 1 deletion x-pack/dev-tools/jest/create_jest_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ export function createJestConfig({ kibanaDirectory, xPackKibanaDirectory }) {
'uiExports/(.*)': fileMockPath,
'^src/core/(.*)': `${kibanaDirectory}/src/core/$1`,
'^src/legacy/(.*)': `${kibanaDirectory}/src/legacy/$1`,
'^plugins/watcher/models/(.*)': `${xPackKibanaDirectory}/legacy/plugins/watcher/public/models/$1`,
'^plugins/watcher/np_ready/application/models/(.*)':
`${xPackKibanaDirectory}/legacy/plugins/watcher/public/np_ready/application/models/$1`,
'^plugins/([^/.]*)(.*)': `${kibanaDirectory}/src/legacy/core_plugins/$1/public$2`,
'^plugins/xpack_main/(.*);': `${xPackKibanaDirectory}/legacy/plugins/xpack_main/public/$1`,
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': fileMockPath,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* 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 React from 'react';
import { ComponentType } from 'enzyme';
import {
chromeServiceMock,
docLinksServiceMock,
uiSettingsServiceMock,
notificationServiceMock,
httpServiceMock,
} from '../../../../../../../src/core/public/mocks';
import { AppContextProvider } from '../../../public/np_ready/application/app_context';

export const mockContextValue = {
docLinks: docLinksServiceMock.createStartContract(),
chrome: chromeServiceMock.createStartContract(),
legacy: {
TimeBuckets: class MockTimeBuckets {
setBounds(_domain: any) {
return {};
}
getInterval() {
return {
expression: {},
};
}
},
MANAGEMENT_BREADCRUMB: { text: 'test' },
licenseStatus: {},
},
uiSettings: uiSettingsServiceMock.createSetupContract(),
toasts: notificationServiceMock.createSetupContract().toasts,
euiUtils: {
useChartsTheme: jest.fn(),
},
// For our test harness, we don't use this mocked out http service
http: httpServiceMock.createSetupContract(),
};

export const withAppContext = (Component: ComponentType<any>) => (props: any) => {
return (
<AppContextProvider value={mockContextValue}>
<Component {...props} />
</AppContextProvider>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@
* you may not use this file except in compliance with the Elastic License.
*/

export { registerFieldsRoutes } from './register_fields_routes';
export const wrapBodyResponse = (obj: object) => JSON.stringify({ body: JSON.stringify(obj) });

export const unwrapBodyResponse = (string: string) => JSON.parse(JSON.parse(string).body);
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => {
const defaultResponse = { watchHistoryItems: [] };
server.respondWith(
'GET',
`${API_ROOT}/watch/:id/history?startTime=*`,
`${API_ROOT}/watch/:id/history`,
mockResponse(defaultResponse, response)
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { setup as watchCreateThresholdSetup } from './watch_create_threshold.hel
import { setup as watchEditSetup } from './watch_edit.helpers';

export { nextTick, getRandomString, findTestSubject, TestBed } from '../../../../../../test_utils';

export { wrapBodyResponse, unwrapBodyResponse } from './body_response';
export { setupEnvironment } from './setup_environment';

export const pageHelpers = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,17 @@
import axios from 'axios';
import axiosXhrAdapter from 'axios/lib/adapters/xhr';
import { init as initHttpRequests } from './http_requests';
import { setHttpClient, setSavedObjectsClient } from '../../../public/lib/api';
import { setHttpClient, setSavedObjectsClient } from '../../../public/np_ready/application/lib/api';

const mockHttpClient = axios.create({ adapter: axiosXhrAdapter });
mockHttpClient.interceptors.response.use(
res => {
return res.data;
},
rej => {
return Promise.reject(rej);
}
);

const mockSavedObjectsClient = () => {
return {
Expand All @@ -23,7 +31,7 @@ export const setupEnvironment = () => {
// @ts-ignore
setHttpClient(mockHttpClient);

setSavedObjectsClient(mockSavedObjectsClient());
setSavedObjectsClient(mockSavedObjectsClient() as any);

return {
server,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { withAppContext } from './app_context.mock';
import { registerTestBed, TestBed, TestBedConfig } from '../../../../../../test_utils';
import { WatchEdit } from '../../../public/sections/watch_edit/components/watch_edit';
import { WatchEdit } from '../../../public/np_ready/application/sections/watch_edit/components/watch_edit';
import { ROUTES, WATCH_TYPES } from '../../../common/constants';
import { registerRouter } from '../../../public/lib/navigation';
import { registerRouter } from '../../../public/np_ready/application/lib/navigation';

const testBedConfig: TestBedConfig = {
memoryRouter: {
Expand All @@ -17,7 +18,7 @@ const testBedConfig: TestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WatchEdit, testBedConfig);
const initTestBed = registerTestBed(withAppContext(WatchEdit), testBedConfig);

export interface WatchCreateJsonTestBed extends TestBed<WatchCreateJsonTestSubjects> {
actions: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { registerTestBed, TestBed, TestBedConfig } from '../../../../../../test_utils';
import { WatchEdit } from '../../../public/sections/watch_edit/components/watch_edit';
import { WatchEdit } from '../../../public/np_ready/application/sections/watch_edit/components/watch_edit';
import { ROUTES, WATCH_TYPES } from '../../../common/constants';
import { registerRouter } from '../../../public/lib/navigation';
import { registerRouter } from '../../../public/np_ready/application/lib/navigation';
import { withAppContext } from './app_context.mock';

const testBedConfig: TestBedConfig = {
memoryRouter: {
Expand All @@ -17,7 +18,7 @@ const testBedConfig: TestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WatchEdit, testBedConfig);
const initTestBed = registerTestBed(withAppContext(WatchEdit), testBedConfig);

export interface WatchCreateThresholdTestBed extends TestBed<WatchCreateThresholdTestSubjects> {
actions: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { registerTestBed, TestBed, TestBedConfig } from '../../../../../../test_utils';
import { WatchEdit } from '../../../public/sections/watch_edit/components/watch_edit';
import { WatchEdit } from '../../../public/np_ready/application/sections/watch_edit/components/watch_edit';
import { ROUTES } from '../../../common/constants';
import { registerRouter } from '../../../public/lib/navigation';
import { registerRouter } from '../../../public/np_ready/application/lib/navigation';
import { WATCH_ID } from './constants';
import { withAppContext } from './app_context.mock';

const testBedConfig: TestBedConfig = {
memoryRouter: {
Expand All @@ -18,7 +19,7 @@ const testBedConfig: TestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WatchEdit, testBedConfig);
const initTestBed = registerTestBed(withAppContext(WatchEdit), testBedConfig);

export interface WatchEditTestBed extends TestBed<WatchEditSubjects> {
actions: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ import {
TestBedConfig,
nextTick,
} from '../../../../../../test_utils';
import { WatchList } from '../../../public/sections/watch_list/components/watch_list';
import { WatchList } from '../../../public/np_ready/application/sections/watch_list/components/watch_list';
import { ROUTES } from '../../../common/constants';
import { withAppContext } from './app_context.mock';

const testBedConfig: TestBedConfig = {
memoryRouter: {
Expand All @@ -23,7 +24,7 @@ const testBedConfig: TestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WatchList, testBedConfig);
const initTestBed = registerTestBed(withAppContext(WatchList), testBedConfig);

export interface WatchListTestBed extends TestBed<WatchListTestSubjects> {
actions: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ import {
TestBedConfig,
nextTick,
} from '../../../../../../test_utils';
import { WatchStatus } from '../../../public/sections/watch_status/components/watch_status';
import { WatchStatus } from '../../../public/np_ready/application/sections/watch_status/components/watch_status';
import { ROUTES } from '../../../common/constants';
import { WATCH_ID } from './constants';
import { withAppContext } from './app_context.mock';

const testBedConfig: TestBedConfig = {
memoryRouter: {
Expand All @@ -25,7 +26,7 @@ const testBedConfig: TestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WatchStatus, testBedConfig);
const initTestBed = registerTestBed(withAppContext(WatchStatus), testBedConfig);

export interface WatchStatusTestBed extends TestBed<WatchStatusTestSubjects> {
actions: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,15 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { act } from 'react-dom/test-utils';
import { setupEnvironment, pageHelpers, nextTick } from './helpers';
import { setupEnvironment, pageHelpers, nextTick, wrapBodyResponse } from './helpers';
import { WatchCreateJsonTestBed } from './helpers/watch_create_json.helpers';
import { WATCH } from './helpers/constants';
import defaultWatchJson from '../../public/models/watch/default_watch.json';
import defaultWatchJson from '../../public/np_ready/application/models/watch/default_watch.json';
import { getExecuteDetails } from '../../test/fixtures';

jest.mock('ui/chrome', () => ({
breadcrumbs: { set: () => {} },
addBasePath: (path: string) => path || '/api/watcher',
}));

jest.mock('ui/time_buckets', () => {});

const { setup } = pageHelpers.watchCreateJson;

describe.skip('<JsonWatchEdit /> create route', () => {
describe('<JsonWatchEdit /> create route', () => {
const { server, httpRequestsMockHelpers } = setupEnvironment();
let testBed: WatchCreateJsonTestBed;

Expand Down Expand Up @@ -107,7 +100,7 @@ describe.skip('<JsonWatchEdit /> create route', () => {
'There are {{ctx.payload.hits.total}} documents in your index. Threshold is 10.';

expect(latestRequest.requestBody).toEqual(
JSON.stringify({
wrapBodyResponse({
id: watch.id,
name: watch.name,
type: watch.type,
Expand Down Expand Up @@ -194,7 +187,7 @@ describe.skip('<JsonWatchEdit /> create route', () => {
};

expect(latestRequest.requestBody).toEqual(
JSON.stringify({
wrapBodyResponse({
executeDetails: getExecuteDetails({
actionModes,
}),
Expand Down Expand Up @@ -258,7 +251,7 @@ describe.skip('<JsonWatchEdit /> create route', () => {
const scheduledTime = `now+${SCHEDULED_TIME}s`;

expect(latestRequest.requestBody).toEqual(
JSON.stringify({
wrapBodyResponse({
executeDetails: getExecuteDetails({
triggerData: {
triggeredTime,
Expand Down
Loading

0 comments on commit 307c124

Please sign in to comment.