Skip to content

Commit 9bda6bd

Browse files
Move ensureDefaultIndexPattern into data plugin (#63100)
* 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>
1 parent 0dcefe8 commit 9bda6bd

File tree

16 files changed

+133
-134
lines changed

16 files changed

+133
-134
lines changed

src/legacy/core_plugins/kibana/public/discover/kibana_services.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,7 @@ export const [getUrlTracker, setUrlTracker] = createGetterSetter<{
5959
export const getHistory = _.once(() => createHashHistory());
6060

6161
export const { getRequestInspectorStats, getResponseInspectorStats, tabifyAggResponse } = search;
62-
export {
63-
unhashUrl,
64-
redirectWhenMissing,
65-
ensureDefaultIndexPattern,
66-
} from '../../../../../plugins/kibana_utils/public';
62+
export { unhashUrl, redirectWhenMissing } from '../../../../../plugins/kibana_utils/public';
6763
export {
6864
formatMsg,
6965
formatStack,

src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ import {
4949
subscribeWithScope,
5050
tabifyAggResponse,
5151
getAngularModule,
52-
ensureDefaultIndexPattern,
5352
redirectWhenMissing,
5453
} from '../../kibana_services';
5554

@@ -118,7 +117,7 @@ app.config($routeProvider => {
118117
savedObjects: function($route, Promise) {
119118
const history = getHistory();
120119
const savedSearchId = $route.current.params.id;
121-
return ensureDefaultIndexPattern(core, data, history).then(() => {
120+
return data.indexPatterns.ensureDefaultIndexPattern(history).then(() => {
122121
const { appStateContainer } = getState({ history });
123122
const { index } = appStateContainer.getState();
124123
return Promise.props({

src/legacy/core_plugins/kibana/public/management/sections/index_patterns/create_index_pattern_wizard/__snapshots__/create_index_pattern_wizard.test.tsx.snap

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/plugins/dashboard/public/application/legacy_app.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ import { initDashboardAppDirective } from './dashboard_app';
2828
import { createDashboardEditUrl, DashboardConstants } from '../dashboard_constants';
2929
import {
3030
createKbnUrlStateStorage,
31-
ensureDefaultIndexPattern,
3231
redirectWhenMissing,
3332
InvalidJSONProperty,
3433
SavedObjectNotFound,
@@ -138,7 +137,7 @@ export function initDashboardApp(app, deps) {
138137
},
139138
resolve: {
140139
dash: function($route, history) {
141-
return ensureDefaultIndexPattern(deps.core, deps.data, history).then(() => {
140+
return deps.data.indexPatterns.ensureDefaultIndexPattern(history).then(() => {
142141
const savedObjectsClient = deps.savedObjectsClient;
143142
const title = $route.current.params.title;
144143
if (title) {
@@ -173,7 +172,8 @@ export function initDashboardApp(app, deps) {
173172
requireUICapability: 'dashboard.createNew',
174173
resolve: {
175174
dash: history =>
176-
ensureDefaultIndexPattern(deps.core, deps.data, history)
175+
deps.data.indexPatterns
176+
.ensureDefaultIndexPattern(history)
177177
.then(() => deps.savedDashboards.get())
178178
.catch(
179179
redirectWhenMissing({
@@ -194,7 +194,8 @@ export function initDashboardApp(app, deps) {
194194
dash: function($route, history) {
195195
const id = $route.current.params.id;
196196

197-
return ensureDefaultIndexPattern(deps.core, deps.data, history)
197+
return deps.data.indexPatterns
198+
.ensureDefaultIndexPattern(history)
198199
.then(() => deps.savedDashboards.get(id))
199200
.then(savedDashboard => {
200201
deps.chrome.recentlyAccessed.add(
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/*
2+
* Licensed to Elasticsearch B.V. under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch B.V. licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
import { contains } from 'lodash';
21+
import React from 'react';
22+
import { History } from 'history';
23+
import { i18n } from '@kbn/i18n';
24+
import { EuiCallOut } from '@elastic/eui';
25+
import { CoreStart } from 'kibana/public';
26+
import { toMountPoint } from '../../../../kibana_react/public';
27+
import { IndexPatternsContract } from './index_patterns';
28+
29+
export type EnsureDefaultIndexPattern = (history: History) => Promise<unknown> | undefined;
30+
31+
export const createEnsureDefaultIndexPattern = (core: CoreStart) => {
32+
let bannerId: string;
33+
let timeoutId: NodeJS.Timeout | undefined;
34+
35+
/**
36+
* Checks whether a default index pattern is set and exists and defines
37+
* one otherwise.
38+
*
39+
* If there are no index patterns, redirect to management page and show
40+
* banner. In this case the promise returned from this function will never
41+
* resolve to wait for the URL change to happen.
42+
*/
43+
return async function ensureDefaultIndexPattern(this: IndexPatternsContract, history: History) {
44+
const patterns = await this.getIds();
45+
let defaultId = core.uiSettings.get('defaultIndex');
46+
let defined = !!defaultId;
47+
const exists = contains(patterns, defaultId);
48+
49+
if (defined && !exists) {
50+
core.uiSettings.remove('defaultIndex');
51+
defaultId = defined = false;
52+
}
53+
54+
if (defined) {
55+
return;
56+
}
57+
58+
// If there is any index pattern created, set the first as default
59+
if (patterns.length >= 1) {
60+
defaultId = patterns[0];
61+
core.uiSettings.set('defaultIndex', defaultId);
62+
} else {
63+
const canManageIndexPatterns = core.application.capabilities.management.kibana.index_patterns;
64+
const redirectTarget = canManageIndexPatterns ? '/management/kibana/index_pattern' : '/home';
65+
66+
if (timeoutId) {
67+
clearTimeout(timeoutId);
68+
}
69+
70+
// Avoid being hostile to new users who don't have an index pattern setup yet
71+
// give them a friendly info message instead of a terse error message
72+
bannerId = core.overlays.banners.replace(
73+
bannerId,
74+
toMountPoint(
75+
<EuiCallOut
76+
color="warning"
77+
iconType="iInCircle"
78+
title={i18n.translate('data.indexPatterns.ensureDefaultIndexPattern.bannerLabel', {
79+
defaultMessage:
80+
"In order to visualize and explore data in Kibana, you'll need to create an index pattern to retrieve data from Elasticsearch.",
81+
})}
82+
/>
83+
)
84+
);
85+
86+
// hide the message after the user has had a chance to acknowledge it -- so it doesn't permanently stick around
87+
timeoutId = setTimeout(() => {
88+
core.overlays.banners.remove(bannerId);
89+
timeoutId = undefined;
90+
}, 15000);
91+
92+
history.push(redirectTarget);
93+
94+
// return never-resolving promise to stop resolving and wait for the url change
95+
return new Promise(() => {});
96+
}
97+
};
98+
};

src/plugins/data/public/index_patterns/index_patterns/index_patterns.test.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@
2121
import { IndexPatternsService } from './index_patterns';
2222
import {
2323
SavedObjectsClientContract,
24-
IUiSettingsClient,
2524
HttpSetup,
2625
SavedObjectsFindResponsePublic,
26+
CoreStart,
2727
} from 'kibana/public';
2828

2929
jest.mock('./index_pattern', () => {
@@ -61,10 +61,10 @@ describe('IndexPatterns', () => {
6161
}) as Promise<SavedObjectsFindResponsePublic<any>>
6262
);
6363

64-
const uiSettings = {} as IUiSettingsClient;
64+
const core = {} as CoreStart;
6565
const http = {} as HttpSetup;
6666

67-
indexPatterns = new IndexPatternsService(uiSettings, savedObjectsClient, http);
67+
indexPatterns = new IndexPatternsService(core, savedObjectsClient, http);
6868
});
6969

7070
test('does cache gets for the same id', async () => {

src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,16 @@ import {
2222
SimpleSavedObject,
2323
IUiSettingsClient,
2424
HttpStart,
25+
CoreStart,
2526
} from 'src/core/public';
2627

2728
import { createIndexPatternCache } from './_pattern_cache';
2829
import { IndexPattern } from './index_pattern';
2930
import { IndexPatternsApiClient, GetFieldsOptions } from './index_patterns_api_client';
31+
import {
32+
createEnsureDefaultIndexPattern,
33+
EnsureDefaultIndexPattern,
34+
} from './ensure_default_index_pattern';
3035

3136
const indexPatternCache = createIndexPatternCache();
3237

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

41-
constructor(
42-
config: IUiSettingsClient,
43-
savedObjectsClient: SavedObjectsClientContract,
44-
http: HttpStart
45-
) {
47+
constructor(core: CoreStart, savedObjectsClient: SavedObjectsClientContract, http: HttpStart) {
4648
this.apiClient = new IndexPatternsApiClient(http);
47-
this.config = config;
49+
this.config = core.uiSettings;
4850
this.savedObjectsClient = savedObjectsClient;
51+
this.ensureDefaultIndexPattern = createEnsureDefaultIndexPattern(core);
4952
}
5053

5154
private async refreshSavedObjectsCache() {

src/plugins/data/public/mocks.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ const createStartContract = (): Start => {
5757
SearchBar: jest.fn(),
5858
},
5959
indexPatterns: ({
60+
ensureDefaultIndexPattern: jest.fn(),
6061
make: () => ({
6162
fieldsFetcher: {
6263
fetchForWildcard: jest.fn(),

src/plugins/data/public/plugin.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ export class DataPublicPlugin implements Plugin<DataPublicPluginSetup, DataPubli
160160
const fieldFormats = this.fieldFormatsService.start();
161161
setFieldFormats(fieldFormats);
162162

163-
const indexPatterns = new IndexPatternsService(uiSettings, savedObjects.client, http);
163+
const indexPatterns = new IndexPatternsService(core, savedObjects.client, http);
164164
setIndexPatterns(indexPatterns);
165165

166166
const query = this.queryService.start(savedObjects);

src/plugins/kibana_utils/public/history/ensure_default_index_pattern.tsx

Lines changed: 0 additions & 98 deletions
This file was deleted.

0 commit comments

Comments
 (0)