Skip to content

Commit

Permalink
fix(initlization): lint
Browse files Browse the repository at this point in the history
  • Loading branch information
Desvelao committed Dec 2, 2024
1 parent 2f3af97 commit 57e345e
Show file tree
Hide file tree
Showing 14 changed files with 620 additions and 463 deletions.
8 changes: 8 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ module.exports = {
'react-hooks',
'@typescript-eslint',
'unicorn',
'import',
'prettier',
'@stylistic',
],
Expand Down Expand Up @@ -210,6 +211,12 @@ module.exports = {
'@typescript-eslint/naming-convention': [
'error',
{ selector: 'default', format: ['camelCase'] },
{ selector: 'import', format: ['camelCase', 'PascalCase'] },
{
selector: 'variable',
types: ['function'],
format: ['camelCase', 'PascalCase'],
},
{
selector: ['objectLiteralProperty', 'typeProperty'],
format: null,
Expand All @@ -225,6 +232,7 @@ module.exports = {
{
selector: ['variable'],
modifiers: ['global'],
types: ['number', 'string'],
format: ['UPPER_CASE'],
},
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import React from 'react';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { EuiButton, EuiEmptyPrompt, EuiLink } from '@elastic/eui';
import { withGuardAsync } from '../../../../common/hocs';
import { getSavedObjects } from '../../../../../kibana-services';
import { SavedObject } from '../../../../../react-services';
import { NOT_TIME_FIELD_NAME_INDEX_PATTERN } from '../../../../../../common/constants';
import { EuiButton, EuiEmptyPrompt, EuiLink } from '@elastic/eui';
import { webDocumentationLink } from '../../../../../../common/services/web_documentation';
import { vulnerabilityDetection } from '../../../../../utils/applications';
import { LoadingSpinnerDataSource } from '../../../../common/loading/loading-spinner-data-source';
import NavigationService from '../../../../../react-services/navigation-service';
import { NavigationService } from '../../../../../react-services/navigation-service';

const INDEX_PATTERN_CREATION_NO_INDEX = 'INDEX_PATTERN_CREATION_NO_INDEX';

Expand All @@ -20,8 +20,9 @@ async function checkExistenceIndexPattern(indexPatternID: string) {
async function checkExistenceIndices(indexPatternId: string) {
try {
const fields = await SavedObject.getIndicesFields(indexPatternId);

return { exist: true, fields };
} catch (error) {
} catch {
return { exist: false };
}
}
Expand Down Expand Up @@ -51,7 +52,7 @@ export async function validateVulnerabilitiesStateDataSources({
try {
// Check the existence of related index pattern
const existIndexPattern = await checkExistenceIndexPattern(indexPatternID);
let indexPattern = existIndexPattern;
const indexPattern = existIndexPattern;

// If the idnex pattern does not exist, then check the existence of index
if (existIndexPattern?.error?.statusCode === 404) {
Expand All @@ -70,11 +71,13 @@ export async function validateVulnerabilitiesStateDataSources({
},
};
}

// If the some index match the index pattern, then create the index pattern
const resultCreateIndexPattern = await createIndexPattern(
indexPatternID,
fields,
);

if (resultCreateIndexPattern?.error) {
return {
ok: true,
Expand All @@ -86,6 +89,7 @@ export async function validateVulnerabilitiesStateDataSources({
},
};
}

/* WORKAROUND: Redirect to the root of Vulnerabilities Detection application that should
redirects to the Dashboard tab. We want to redirect to this view, because we need the
component is visible (visualizations) to ensure the process that defines the filters for the
Expand All @@ -95,6 +99,7 @@ export async function validateVulnerabilitiesStateDataSources({
*/
NavigationService.getInstance().navigateToApp(vulnerabilityDetection.id);
}

return {
ok: false,
data: { indexPattern },
Expand Down Expand Up @@ -127,10 +132,13 @@ const errorPromptBody = {
),
};

export const PromptCheckIndex = props => {
export const PromptCheckIndex = (props: {
error: { title: string; message: string; type?: string };
refresh: () => void;
}) => {
const { refresh } = props;
const { title, message } = props?.error;
const body = errorPromptBody?.[props?.error?.type] || <p>{message}</p>;
const { title, message } = props.error;
const body = errorPromptBody?.[props.error?.type] || <p>{message}</p>;

return (
<EuiEmptyPrompt
Expand All @@ -146,10 +154,12 @@ export const PromptCheckIndex = props => {
);
};

const mapStateToProps = state => ({
vulnerabilitiesStatesindexPatternID:
state.appConfig.data['vulnerabilities.pattern'],
});
const mapStateToProps = state => {
return {
vulnerabilitiesStatesindexPatternID:
state.appConfig.data['vulnerabilities.pattern'],
};
};

export const withVulnerabilitiesStateDataSource = compose(
connect(mapStateToProps),
Expand Down
93 changes: 55 additions & 38 deletions plugins/main/public/react-services/navigation-service.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Location, Action, History } from 'history';
import rison from 'rison-node';
import { getCore } from '../kibana-services';
import { NavigateToAppOptions } from '../../../../src/core/public';
import { getIndexPattern } from './elastic_helpers';
import { buildPhraseFilter } from '../../../../src/plugins/data/common';
import rison from 'rison-node';
import { getIndexPattern } from './elastic_helpers';

class NavigationService {
// eslint-disable-next-line no-use-before-define
private static instance: NavigationService;
private history: History;
private readonly history: History;

private constructor(history: History) {
this.history = history;
Expand All @@ -19,6 +20,7 @@ class NavigationService {
} else if (!NavigationService.instance) {
throw new Error('NavigationService must be initialized with a history.');
}

return NavigationService.instance;
}

Expand Down Expand Up @@ -56,30 +58,31 @@ class NavigationService {
? this.buildSearch(params)
: this.buildSearch(this.getParams());
const locationHash = this.getHash();

this.navigate(
`${newPath}${queryParams ? `?${queryParams}` : ''}${locationHash}`,
);
}

public navigate(path: string, state?: any): void {
if (!state) {
this.history.push(path);
} else {
if (state) {
this.history.push({
pathname: path,
state,
});
} else {
this.history.push(path);
}
}

public replace(path: string, state?: any): void {
if (!state) {
this.history.replace(path);
} else {
if (state) {
this.history.replace({
pathname: path,
state,
});
} else {
this.history.replace(path);
}
}

Expand All @@ -96,13 +99,14 @@ class NavigationService {
}

public reload(): void {
window.location.reload();
globalThis.location.reload();
}

public listen(
listener: (location: Location, action: Action) => void,
): () => void {
const unlisten = this.history.listen(listener);

return unlisten;
}

Expand All @@ -125,43 +129,45 @@ class NavigationService {
}

public buildSearch(search: URLSearchParams) {
return Array.from(search.entries())
return [...search.entries()]
.map(([key, value]) => `${key}=${value}`)
.join('&');
}

public updateAndNavigateSearchParams(params: {
[key: string]: string | null;
}): void {
public updateAndNavigateSearchParams(
params: Record<string, string | null>,
): void {
const urlParams = this.getParams();

// Update or delete parameters according to their value
Object.entries(params).forEach(([key, value]) => {
for (const [key, value] of Object.entries(params)) {
if (value === null) {
urlParams.delete(key);
} else {
urlParams.set(key, value);
}
});
}

const queryString = this.buildSearch(urlParams);

this.navigate(`${this.getPathname()}?${queryString}`);
}

public switchTab(newTab: string): void {
this.updateAndNavigateSearchParams({ tab: newTab });
}

public switchSubTab = (subTab: string): void => {
public switchSubTab(subTab: string): void {
this.updateAndNavigateSearchParams({ tabView: subTab });
};
}

/*
TODO: Analyze and improve this function taking into account whether buildFilter_w is still used and whether the implementation with respect to the middle button is correct in navigateToModule
TODO: Analyze and improve this function taking into account whether buildFilterW is still used and whether the implementation with respect to the middle button is correct in navigateToModule
*/
private buildFilter_w(filters, indexPattern) {
private buildFilterW(filters, indexPattern) {
const filtersArray: any[] = [];
Object.keys(filters).forEach(currentFilter => {

for (const currentFilter of Object.keys(filters)) {
filtersArray.push({
...buildPhraseFilter(
{ name: currentFilter, type: 'text' },
Expand All @@ -170,41 +176,51 @@ class NavigationService {
),
$state: { isImplicit: false, store: 'appState' },
});
});
}

return rison.encode({ filters: filtersArray });
}

navigateToModule(e: any, section: string, params: any, navigateMethod?: any) {
e.persist(); // needed to access this event asynchronously
if (e.button == 0) {
// left button clicked
if (navigateMethod) {
navigateMethod();
return;
}
navigateToModule(
event: any,
section: string,
params: any,
navigateMethod?: any,
) {
event.persist(); // needed to access this event asynchronously

if (
event.button === 0 && // left button clicked
navigateMethod
) {
navigateMethod();

return;
}

getIndexPattern().then(indexPattern => {
const urlParams = {};

if (Object.keys(params).length) {
Object.keys(params).forEach(key => {
if (Object.keys(params).length > 0) {
for (const key of Object.keys(params)) {
if (key === 'filters') {
urlParams['_w'] = this.buildFilter_w(params[key], indexPattern);
urlParams['_w'] = this.buildFilterW(params[key], indexPattern);
} else {
urlParams[key] = params[key];
}
});
}
}

const url = Object.entries(urlParams)
.map(e => e.join('='))
.map(urlParam => urlParam.join('='))
.join('&');
const currentUrl = window.location.href.split('#/')[0];
const currentUrl = globalThis.location.href.split('#/')[0];
const newUrl = currentUrl + `#/${section}?` + url;

if (e && (e.which == 2 || e.button == 1)) {
if (event && (event.which === 2 || event.button === 1)) {
// middlebutton clicked
window.open(newUrl, '_blank', 'noreferrer');
} else if (e.button == 0) {
} else if (event.button === 0) {
// left button clicked
if (navigateMethod) {
navigateMethod();
Expand All @@ -217,3 +233,4 @@ class NavigationService {
}

export default NavigationService;
export { NavigationService };
Loading

0 comments on commit 57e345e

Please sign in to comment.