Skip to content

Commit

Permalink
Move ensureDefaultIndexPattern into data plugin (#63100)
Browse files Browse the repository at this point in the history
* Move ensure_default_index_pattern into data plugin

* Update docs to include ensureDefaultIndexPattern

* Fix translations

* Move helper into index_patterns service

* Update docs

* Remove mock

* Add mock

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
  • Loading branch information
sulemanof and elasticmachine authored Apr 24, 2020
1 parent 0dcefe8 commit 9bda6bd
Show file tree
Hide file tree
Showing 16 changed files with 133 additions and 134 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,7 @@ export const [getUrlTracker, setUrlTracker] = createGetterSetter<{
export const getHistory = _.once(() => createHashHistory());

export const { getRequestInspectorStats, getResponseInspectorStats, tabifyAggResponse } = search;
export {
unhashUrl,
redirectWhenMissing,
ensureDefaultIndexPattern,
} from '../../../../../plugins/kibana_utils/public';
export { unhashUrl, redirectWhenMissing } from '../../../../../plugins/kibana_utils/public';
export {
formatMsg,
formatStack,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ import {
subscribeWithScope,
tabifyAggResponse,
getAngularModule,
ensureDefaultIndexPattern,
redirectWhenMissing,
} from '../../kibana_services';

Expand Down Expand Up @@ -118,7 +117,7 @@ app.config($routeProvider => {
savedObjects: function($route, Promise) {
const history = getHistory();
const savedSearchId = $route.current.params.id;
return ensureDefaultIndexPattern(core, data, history).then(() => {
return data.indexPatterns.ensureDefaultIndexPattern(history).then(() => {
const { appStateContainer } = getState({ history });
const { index } = appStateContainer.getState();
return Promise.props({
Expand Down

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

9 changes: 5 additions & 4 deletions src/plugins/dashboard/public/application/legacy_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import { initDashboardAppDirective } from './dashboard_app';
import { createDashboardEditUrl, DashboardConstants } from '../dashboard_constants';
import {
createKbnUrlStateStorage,
ensureDefaultIndexPattern,
redirectWhenMissing,
InvalidJSONProperty,
SavedObjectNotFound,
Expand Down Expand Up @@ -138,7 +137,7 @@ export function initDashboardApp(app, deps) {
},
resolve: {
dash: function($route, history) {
return ensureDefaultIndexPattern(deps.core, deps.data, history).then(() => {
return deps.data.indexPatterns.ensureDefaultIndexPattern(history).then(() => {
const savedObjectsClient = deps.savedObjectsClient;
const title = $route.current.params.title;
if (title) {
Expand Down Expand Up @@ -173,7 +172,8 @@ export function initDashboardApp(app, deps) {
requireUICapability: 'dashboard.createNew',
resolve: {
dash: history =>
ensureDefaultIndexPattern(deps.core, deps.data, history)
deps.data.indexPatterns
.ensureDefaultIndexPattern(history)
.then(() => deps.savedDashboards.get())
.catch(
redirectWhenMissing({
Expand All @@ -194,7 +194,8 @@ export function initDashboardApp(app, deps) {
dash: function($route, history) {
const id = $route.current.params.id;

return ensureDefaultIndexPattern(deps.core, deps.data, history)
return deps.data.indexPatterns
.ensureDefaultIndexPattern(history)
.then(() => deps.savedDashboards.get(id))
.then(savedDashboard => {
deps.chrome.recentlyAccessed.add(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { contains } from 'lodash';
import React from 'react';
import { History } from 'history';
import { i18n } from '@kbn/i18n';
import { EuiCallOut } from '@elastic/eui';
import { CoreStart } from 'kibana/public';
import { toMountPoint } from '../../../../kibana_react/public';
import { IndexPatternsContract } from './index_patterns';

export type EnsureDefaultIndexPattern = (history: History) => Promise<unknown> | undefined;

export const createEnsureDefaultIndexPattern = (core: CoreStart) => {
let bannerId: string;
let timeoutId: NodeJS.Timeout | undefined;

/**
* Checks whether a default index pattern is set and exists and defines
* one otherwise.
*
* If there are no index patterns, redirect to management page and show
* banner. In this case the promise returned from this function will never
* resolve to wait for the URL change to happen.
*/
return async function ensureDefaultIndexPattern(this: IndexPatternsContract, history: History) {
const patterns = await this.getIds();
let defaultId = core.uiSettings.get('defaultIndex');
let defined = !!defaultId;
const exists = contains(patterns, defaultId);

if (defined && !exists) {
core.uiSettings.remove('defaultIndex');
defaultId = defined = false;
}

if (defined) {
return;
}

// If there is any index pattern created, set the first as default
if (patterns.length >= 1) {
defaultId = patterns[0];
core.uiSettings.set('defaultIndex', defaultId);
} else {
const canManageIndexPatterns = core.application.capabilities.management.kibana.index_patterns;
const redirectTarget = canManageIndexPatterns ? '/management/kibana/index_pattern' : '/home';

if (timeoutId) {
clearTimeout(timeoutId);
}

// Avoid being hostile to new users who don't have an index pattern setup yet
// give them a friendly info message instead of a terse error message
bannerId = core.overlays.banners.replace(
bannerId,
toMountPoint(
<EuiCallOut
color="warning"
iconType="iInCircle"
title={i18n.translate('data.indexPatterns.ensureDefaultIndexPattern.bannerLabel', {
defaultMessage:
"In order to visualize and explore data in Kibana, you'll need to create an index pattern to retrieve data from Elasticsearch.",
})}
/>
)
);

// hide the message after the user has had a chance to acknowledge it -- so it doesn't permanently stick around
timeoutId = setTimeout(() => {
core.overlays.banners.remove(bannerId);
timeoutId = undefined;
}, 15000);

history.push(redirectTarget);

// return never-resolving promise to stop resolving and wait for the url change
return new Promise(() => {});
}
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
import { IndexPatternsService } from './index_patterns';
import {
SavedObjectsClientContract,
IUiSettingsClient,
HttpSetup,
SavedObjectsFindResponsePublic,
CoreStart,
} from 'kibana/public';

jest.mock('./index_pattern', () => {
Expand Down Expand Up @@ -61,10 +61,10 @@ describe('IndexPatterns', () => {
}) as Promise<SavedObjectsFindResponsePublic<any>>
);

const uiSettings = {} as IUiSettingsClient;
const core = {} as CoreStart;
const http = {} as HttpSetup;

indexPatterns = new IndexPatternsService(uiSettings, savedObjectsClient, http);
indexPatterns = new IndexPatternsService(core, savedObjectsClient, http);
});

test('does cache gets for the same id', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,16 @@ import {
SimpleSavedObject,
IUiSettingsClient,
HttpStart,
CoreStart,
} from 'src/core/public';

import { createIndexPatternCache } from './_pattern_cache';
import { IndexPattern } from './index_pattern';
import { IndexPatternsApiClient, GetFieldsOptions } from './index_patterns_api_client';
import {
createEnsureDefaultIndexPattern,
EnsureDefaultIndexPattern,
} from './ensure_default_index_pattern';

const indexPatternCache = createIndexPatternCache();

Expand All @@ -37,15 +42,13 @@ export class IndexPatternsService {
private savedObjectsClient: SavedObjectsClientContract;
private savedObjectsCache?: Array<SimpleSavedObject<Record<string, any>>> | null;
private apiClient: IndexPatternsApiClient;
ensureDefaultIndexPattern: EnsureDefaultIndexPattern;

constructor(
config: IUiSettingsClient,
savedObjectsClient: SavedObjectsClientContract,
http: HttpStart
) {
constructor(core: CoreStart, savedObjectsClient: SavedObjectsClientContract, http: HttpStart) {
this.apiClient = new IndexPatternsApiClient(http);
this.config = config;
this.config = core.uiSettings;
this.savedObjectsClient = savedObjectsClient;
this.ensureDefaultIndexPattern = createEnsureDefaultIndexPattern(core);
}

private async refreshSavedObjectsCache() {
Expand Down
1 change: 1 addition & 0 deletions src/plugins/data/public/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const createStartContract = (): Start => {
SearchBar: jest.fn(),
},
indexPatterns: ({
ensureDefaultIndexPattern: jest.fn(),
make: () => ({
fieldsFetcher: {
fetchForWildcard: jest.fn(),
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/data/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export class DataPublicPlugin implements Plugin<DataPublicPluginSetup, DataPubli
const fieldFormats = this.fieldFormatsService.start();
setFieldFormats(fieldFormats);

const indexPatterns = new IndexPatternsService(uiSettings, savedObjects.client, http);
const indexPatterns = new IndexPatternsService(core, savedObjects.client, http);
setIndexPatterns(indexPatterns);

const query = this.queryService.start(savedObjects);
Expand Down

This file was deleted.

1 change: 0 additions & 1 deletion src/plugins/kibana_utils/public/history/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,3 @@

export { removeQueryParam } from './remove_query_param';
export { redirectWhenMissing } from './redirect_when_missing';
export { ensureDefaultIndexPattern } from './ensure_default_index_pattern';
2 changes: 1 addition & 1 deletion src/plugins/kibana_utils/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export {
StartSyncStateFnType,
StopSyncStateFnType,
} from './state_sync';
export { removeQueryParam, redirectWhenMissing, ensureDefaultIndexPattern } from './history';
export { removeQueryParam, redirectWhenMissing } from './history';
export { applyDiff } from './state_management/utils/diff_object';

/** dummy plugin, we just want kibanaUtils to have its own bundle */
Expand Down

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

Loading

0 comments on commit 9bda6bd

Please sign in to comment.