replace any with unknown in http client and types (#114265)

This commit is contained in:
Or Ouziel 2021-11-02 13:53:56 +02:00 committed by GitHub
parent 29e807f2e2
commit f2b9acf67b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
169 changed files with 732 additions and 428 deletions

View file

@ -8,7 +8,7 @@
<b>Signature:</b>
```typescript
export interface HttpResponse<TResponseBody = any>
export interface HttpResponse<TResponseBody = unknown>
```
## Properties

View file

@ -7,5 +7,5 @@
<b>Signature:</b>
```typescript
readonly body?: any;
readonly body?: TResponseBody;
```

View file

@ -8,14 +8,14 @@
<b>Signature:</b>
```typescript
export interface IHttpFetchError extends Error
export interface IHttpFetchError<TResponseBody = unknown> extends Error
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [body](./kibana-plugin-core-public.ihttpfetcherror.body.md) | <code>any</code> | |
| [body](./kibana-plugin-core-public.ihttpfetcherror.body.md) | <code>TResponseBody</code> | |
| [name](./kibana-plugin-core-public.ihttpfetcherror.name.md) | <code>string</code> | |
| [req](./kibana-plugin-core-public.ihttpfetcherror.req.md) | <code>Request</code> | |
| [request](./kibana-plugin-core-public.ihttpfetcherror.request.md) | <code>Request</code> | |

View file

@ -9,7 +9,7 @@ Properties that can be returned by HttpInterceptor.request to override the respo
<b>Signature:</b>
```typescript
export interface IHttpResponseInterceptorOverrides<TResponseBody = any>
export interface IHttpResponseInterceptorOverrides<TResponseBody = unknown>
```
## Properties

View file

@ -97,6 +97,7 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [Plugin](./kibana-plugin-core-public.plugin.md) | The interface that should be returned by a <code>PluginInitializer</code>. |
| [PluginInitializerContext](./kibana-plugin-core-public.plugininitializercontext.md) | The available core services passed to a <code>PluginInitializer</code> |
| [ResolvedSimpleSavedObject](./kibana-plugin-core-public.resolvedsimplesavedobject.md) | This interface is a very simple wrapper for SavedObjects resolved from the server with the [SavedObjectsClient](./kibana-plugin-core-public.savedobjectsclient.md)<!-- -->. |
| [ResponseErrorBody](./kibana-plugin-core-public.responseerrorbody.md) | |
| [SavedObject](./kibana-plugin-core-public.savedobject.md) | |
| [SavedObjectAttributes](./kibana-plugin-core-public.savedobjectattributes.md) | The data for a Saved Object is stored as an object in the <code>attributes</code> property. |
| [SavedObjectError](./kibana-plugin-core-public.savedobjecterror.md) | |

View file

@ -0,0 +1,11 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-public](./kibana-plugin-core-public.md) &gt; [ResponseErrorBody](./kibana-plugin-core-public.responseerrorbody.md) &gt; [attributes](./kibana-plugin-core-public.responseerrorbody.attributes.md)
## ResponseErrorBody.attributes property
<b>Signature:</b>
```typescript
attributes?: Record<string, unknown>;
```

View file

@ -0,0 +1,21 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-public](./kibana-plugin-core-public.md) &gt; [ResponseErrorBody](./kibana-plugin-core-public.responseerrorbody.md)
## ResponseErrorBody interface
<b>Signature:</b>
```typescript
export interface ResponseErrorBody
```
## Properties
| Property | Type | Description |
| --- | --- | --- |
| [attributes](./kibana-plugin-core-public.responseerrorbody.attributes.md) | <code>Record&lt;string, unknown&gt;</code> | |
| [message](./kibana-plugin-core-public.responseerrorbody.message.md) | <code>string</code> | |
| [statusCode](./kibana-plugin-core-public.responseerrorbody.statuscode.md) | <code>number</code> | |

View file

@ -0,0 +1,11 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-public](./kibana-plugin-core-public.md) &gt; [ResponseErrorBody](./kibana-plugin-core-public.responseerrorbody.md) &gt; [message](./kibana-plugin-core-public.responseerrorbody.message.md)
## ResponseErrorBody.message property
<b>Signature:</b>
```typescript
message: string;
```

View file

@ -0,0 +1,11 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) &gt; [kibana-plugin-core-public](./kibana-plugin-core-public.md) &gt; [ResponseErrorBody](./kibana-plugin-core-public.responseerrorbody.md) &gt; [statusCode](./kibana-plugin-core-public.responseerrorbody.statuscode.md)
## ResponseErrorBody.statusCode property
<b>Signature:</b>
```typescript
statusCode: number;
```

View file

@ -17,7 +17,7 @@ import {
EuiText,
} from '@elastic/eui';
import React, { useEffect, useState } from 'react';
import type { HttpSetup, IHttpFetchError } from 'src/core/public';
import type { HttpSetup, IHttpFetchError, ResponseErrorBody } from 'src/core/public';
export const App = ({ http, token }: { http: HttpSetup; token?: string }) => {
const onCompleteSetup = async ({ shouldReloadConfig }: { shouldReloadConfig: boolean }) => {
@ -41,7 +41,8 @@ export const App = ({ http, token }: { http: HttpSetup; token?: string }) => {
.post('/api/preboot/connect_to_es', { body: JSON.stringify(elasticsearchConfig) })
.then(
(response) => setConnectResponse(JSON.stringify(response)),
(err: IHttpFetchError) => setConnectResponse(err?.body?.message || 'ERROR')
(err: IHttpFetchError<ResponseErrorBody>) =>
setConnectResponse(err?.body?.message || 'ERROR')
);
};

View file

@ -438,7 +438,7 @@ describe('Fetch', () => {
headers: { 'Content-Type': 'application/ndjson' },
});
const data = await fetchInstance.post('/my/path', {
const data = await fetchInstance.post<FormData>('/my/path', {
body,
headers: {
'Content-Type': undefined,

View file

@ -92,9 +92,9 @@ export class Fetch {
);
if (optionsWithPath.asResponse) {
resolve(interceptedResponse);
resolve(interceptedResponse as HttpResponse<TResponseBody>);
} else {
resolve(interceptedResponse.body);
resolve(interceptedResponse.body as TResponseBody);
}
} catch (error) {
if (!(error instanceof HttpInterceptHaltError)) {
@ -142,7 +142,9 @@ export class Fetch {
return new Request(url, fetchOptions as RequestInit);
}
private async fetchResponse(fetchOptions: HttpFetchOptionsWithPath): Promise<HttpResponse<any>> {
private async fetchResponse(
fetchOptions: HttpFetchOptionsWithPath
): Promise<HttpResponse<unknown>> {
const request = this.createRequest(fetchOptions);
let response: Response;
let body = null;
@ -181,9 +183,15 @@ export class Fetch {
}
private shorthand(method: string): HttpHandler {
return (pathOrOptions: string | HttpFetchOptionsWithPath, options?: HttpFetchOptions) => {
const optionsWithPath = validateFetchArguments(pathOrOptions, options);
return this.fetch({ ...optionsWithPath, method });
return <T = unknown>(
pathOrOptions: string | HttpFetchOptionsWithPath,
options?: HttpFetchOptions
) => {
const optionsWithPath: HttpFetchOptionsWithPath = validateFetchArguments(
pathOrOptions,
options
);
return this.fetch<HttpResponse<T>>({ ...optionsWithPath, method });
};
}
}

View file

@ -296,18 +296,19 @@ export interface HttpFetchOptionsWithPath extends HttpFetchOptions {
* @public
*/
export interface HttpHandler {
<TResponseBody = any>(path: string, options: HttpFetchOptions & { asResponse: true }): Promise<
<TResponseBody = unknown>(
path: string,
options: HttpFetchOptions & { asResponse: true }
): Promise<HttpResponse<TResponseBody>>;
<TResponseBody = unknown>(options: HttpFetchOptionsWithPath & { asResponse: true }): Promise<
HttpResponse<TResponseBody>
>;
<TResponseBody = any>(options: HttpFetchOptionsWithPath & { asResponse: true }): Promise<
HttpResponse<TResponseBody>
>;
<TResponseBody = any>(path: string, options?: HttpFetchOptions): Promise<TResponseBody>;
<TResponseBody = any>(options: HttpFetchOptionsWithPath): Promise<TResponseBody>;
<TResponseBody = unknown>(path: string, options?: HttpFetchOptions): Promise<TResponseBody>;
<TResponseBody = unknown>(options: HttpFetchOptionsWithPath): Promise<TResponseBody>;
}
/** @public */
export interface HttpResponse<TResponseBody = any> {
export interface HttpResponse<TResponseBody = unknown> {
/** The original {@link HttpFetchOptionsWithPath} used to send this request. */
readonly fetchOptions: Readonly<HttpFetchOptionsWithPath>;
/** Raw request sent to Kibana server. */
@ -322,7 +323,7 @@ export interface HttpResponse<TResponseBody = any> {
* Properties that can be returned by HttpInterceptor.request to override the response.
* @public
*/
export interface IHttpResponseInterceptorOverrides<TResponseBody = any> {
export interface IHttpResponseInterceptorOverrides<TResponseBody = unknown> {
/** Raw response received, may be undefined if there was an error. */
readonly response?: Readonly<Response>;
/** Parsed body received, may be undefined if there was an error. */
@ -330,7 +331,14 @@ export interface IHttpResponseInterceptorOverrides<TResponseBody = any> {
}
/** @public */
export interface IHttpFetchError extends Error {
export interface ResponseErrorBody {
message: string;
statusCode: number;
attributes?: Record<string, unknown>;
}
/** @public */
export interface IHttpFetchError<TResponseBody = unknown> extends Error {
readonly name: string;
readonly request: Request;
readonly response?: Response;
@ -342,7 +350,7 @@ export interface IHttpFetchError extends Error {
* @deprecated Provided for legacy compatibility. Prefer the `response` property instead.
*/
readonly res?: Response;
readonly body?: any; // TODO: this should be unknown
readonly body?: TResponseBody;
}
/** @public */

View file

@ -157,6 +157,7 @@ export type {
IAnonymousPaths,
IExternalUrl,
IHttpInterceptController,
ResponseErrorBody,
IHttpFetchError,
IHttpResponseInterceptorOverrides,
} from './http';

View file

@ -805,17 +805,17 @@ export interface HttpFetchQuery {
// @public
export interface HttpHandler {
// (undocumented)
<TResponseBody = any>(path: string, options: HttpFetchOptions & {
<TResponseBody = unknown>(path: string, options: HttpFetchOptions & {
asResponse: true;
}): Promise<HttpResponse<TResponseBody>>;
// (undocumented)
<TResponseBody = any>(options: HttpFetchOptionsWithPath & {
<TResponseBody = unknown>(options: HttpFetchOptionsWithPath & {
asResponse: true;
}): Promise<HttpResponse<TResponseBody>>;
// (undocumented)
<TResponseBody = any>(path: string, options?: HttpFetchOptions): Promise<TResponseBody>;
<TResponseBody = unknown>(path: string, options?: HttpFetchOptions): Promise<TResponseBody>;
// (undocumented)
<TResponseBody = any>(options: HttpFetchOptionsWithPath): Promise<TResponseBody>;
<TResponseBody = unknown>(options: HttpFetchOptionsWithPath): Promise<TResponseBody>;
}
// @public
@ -867,7 +867,7 @@ export interface HttpRequestInit {
}
// @public (undocumented)
export interface HttpResponse<TResponseBody = any> {
export interface HttpResponse<TResponseBody = unknown> {
readonly body?: TResponseBody;
readonly fetchOptions: Readonly<HttpFetchOptionsWithPath>;
readonly request: Readonly<Request>;
@ -934,9 +934,9 @@ export interface IExternalUrlPolicy {
}
// @public (undocumented)
export interface IHttpFetchError extends Error {
export interface IHttpFetchError<TResponseBody = unknown> extends Error {
// (undocumented)
readonly body?: any;
readonly body?: TResponseBody;
// (undocumented)
readonly name: string;
// @deprecated (undocumented)
@ -956,7 +956,7 @@ export interface IHttpInterceptController {
}
// @public
export interface IHttpResponseInterceptorOverrides<TResponseBody = any> {
export interface IHttpResponseInterceptorOverrides<TResponseBody = unknown> {
readonly body?: TResponseBody;
readonly response?: Readonly<Response>;
}
@ -1188,6 +1188,16 @@ export interface ResolvedSimpleSavedObject<T = unknown> {
saved_object: SimpleSavedObject<T>;
}
// @public (undocumented)
export interface ResponseErrorBody {
// (undocumented)
attributes?: Record<string, unknown>;
// (undocumented)
message: string;
// (undocumented)
statusCode: number;
}
// Warning: (ae-missing-release-tag) "SavedObject" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)

View file

@ -292,7 +292,7 @@ export class SavedObjectsClient {
overwrite: options.overwrite,
};
const createRequest: Promise<SavedObject<T>> = this.savedObjectsFetch(path, {
const createRequest = this.savedObjectsFetch<SavedObject<T>>(path, {
method: 'POST',
query,
body: JSON.stringify({
@ -571,10 +571,10 @@ export class SavedObjectsClient {
upsert,
};
return this.savedObjectsFetch(path, {
return this.savedObjectsFetch<SavedObject<T>>(path, {
method: 'PUT',
body: JSON.stringify(body),
}).then((resp: SavedObject<T>) => {
}).then((resp) => {
return this.createSavedObject(resp);
});
}
@ -588,11 +588,11 @@ export class SavedObjectsClient {
public bulkUpdate<T = unknown>(objects: SavedObjectsBulkUpdateObject[] = []) {
const path = this.getPath(['_bulk_update']);
return this.savedObjectsFetch(path, {
return this.savedObjectsFetch<{ saved_objects: Array<SavedObject<T>> }>(path, {
method: 'PUT',
body: JSON.stringify(objects),
}).then((resp) => {
resp.saved_objects = resp.saved_objects.map((d: SavedObject<T>) => this.createSavedObject(d));
resp.saved_objects = resp.saved_objects.map((d) => this.createSavedObject(d));
return renameKeys<
PromiseType<ReturnType<SavedObjectsApi['bulkUpdate']>>,
SavedObjectsBatchResponse
@ -624,8 +624,8 @@ export class SavedObjectsClient {
* the old kfetch error format of `{res: {status: number}}` whereas `http.fetch`
* uses `{response: {status: number}}`.
*/
private savedObjectsFetch(path: string, { method, query, body }: HttpFetchOptions) {
return this.http.fetch(path, { method, query, body });
private savedObjectsFetch<T = unknown>(path: string, { method, query, body }: HttpFetchOptions) {
return this.http.fetch<T>(path, { method, query, body });
}
}

View file

@ -56,7 +56,7 @@ export const setupValueSuggestionProvider = (
}
const requestSuggestions = memoize(
(
<T = unknown>(
index: string,
field: IFieldType,
query: string,
@ -68,7 +68,7 @@ export const setupValueSuggestionProvider = (
) => {
usageCollector?.trackRequest();
return core.http
.fetch(`/api/kibana/suggestions/values/${index}`, {
.fetch<T>(`/api/kibana/suggestions/values/${index}`, {
method: 'POST',
body: JSON.stringify({
query,

View file

@ -12,14 +12,14 @@ import { SavedQueryAttributes } from '../../../common';
export const createSavedQueryService = (http: HttpStart) => {
const createQuery = async (attributes: SavedQueryAttributes, { overwrite = false } = {}) => {
const savedQuery = await http.post('/api/saved_query/_create', {
const savedQuery = await http.post<SavedQuery>('/api/saved_query/_create', {
body: JSON.stringify(attributes),
});
return savedQuery;
};
const updateQuery = async (id: string, attributes: SavedQueryAttributes) => {
const savedQuery = await http.put(`/api/saved_query/${id}`, {
const savedQuery = await http.put<SavedQuery>(`/api/saved_query/${id}`, {
body: JSON.stringify(attributes),
});
return savedQuery;
@ -27,9 +27,10 @@ export const createSavedQueryService = (http: HttpStart) => {
// we have to tell the saved objects client how many to fetch, otherwise it defaults to fetching 20 per page
const getAllSavedQueries = async (): Promise<SavedQuery[]> => {
const { savedQueries } = await http.post('/api/saved_query/_find', {
body: JSON.stringify({ perPage: 10000 }),
});
const { savedQueries } = await http.post<{ savedQueries: SavedQuery[] }>(
'/api/saved_query/_find',
{ body: JSON.stringify({ perPage: 10000 }) }
);
return savedQueries;
};
@ -39,7 +40,10 @@ export const createSavedQueryService = (http: HttpStart) => {
perPage: number = 50,
page: number = 1
): Promise<{ total: number; queries: SavedQuery[] }> => {
const { total, savedQueries: queries } = await http.post('/api/saved_query/_find', {
const { total, savedQueries: queries } = await http.post<{
savedQueries: SavedQuery[];
total: number;
}>('/api/saved_query/_find', {
body: JSON.stringify({ page, perPage, search }),
});
@ -47,15 +51,15 @@ export const createSavedQueryService = (http: HttpStart) => {
};
const getSavedQuery = (id: string): Promise<SavedQuery> => {
return http.get(`/api/saved_query/${id}`);
return http.get<SavedQuery>(`/api/saved_query/${id}`);
};
const deleteSavedQuery = (id: string) => {
return http.delete(`/api/saved_query/${id}`);
return http.delete<{}>(`/api/saved_query/${id}`);
};
const getSavedQueryCount = async (): Promise<number> => {
return http.get('/api/saved_query/_count');
return http.get<number>('/api/saved_query/_count');
};
return {

View file

@ -19,9 +19,9 @@ export class DataViewsApiClient implements IDataViewsApiClient {
this.http = http;
}
private _request(url: string, query?: any) {
private _request<T = unknown>(url: string, query?: any) {
return this.http
.fetch(url, {
.fetch<T>(url, {
query,
})
.catch((resp: any) => {
@ -60,7 +60,9 @@ export class DataViewsApiClient implements IDataViewsApiClient {
}
async hasUserIndexPattern(): Promise<boolean> {
const response = await this._request(this._getUrl(['has_user_index_pattern']));
const response = await this._request<{ result: boolean }>(
this._getUrl(['has_user_index_pattern'])
);
return response.result;
}
}

View file

@ -31,7 +31,7 @@ export const sendRequest = async <D = any, E = any>(
): Promise<SendRequestResponse<D, E>> => {
try {
const stringifiedBody = typeof body === 'string' ? body : JSON.stringify(body);
const response = await httpClient[method](path, {
const response = await httpClient[method]<{ data?: D } & D>(path, {
body: stringifiedBody,
query,
asSystemRequest,

View file

@ -167,7 +167,7 @@ const IndexPatternEditorFlyoutContentComponent = ({
useEffect(() => {
const getRollups = async () => {
try {
const response = await http.get('/api/rollup/indices');
const response = await http.get<RollupIndicesCapsResponse>('/api/rollup/indices');
if (response) {
setRollupIndicesCapabilities(response);
}

View file

@ -18,7 +18,10 @@ export const executeScript = async ({
http,
}: ExecuteScriptParams): Promise<ExecuteScriptResult> => {
return http
.post('/internal/index-pattern-management/preview_scripted_field', {
.post<{
statusCode: ExecuteScriptResult['status'];
body: { hits: ExecuteScriptResult['hits'] };
}>('/internal/index-pattern-management/preview_scripted_field', {
body: JSON.stringify({
index: indexPatternTitle,
name,

View file

@ -21,12 +21,12 @@ export const getEnabledScriptingLanguages = (
http: HttpStart,
toasts: NotificationsStart['toasts']
) =>
http.get('/api/kibana/scripts/languages').catch(() => {
http.get<estypes.ScriptLanguage[]>('/api/kibana/scripts/languages').catch(() => {
toasts.addDanger(
i18n.translate('indexPatternManagement.scriptingLanguages.errorFetchingToastDescription', {
defaultMessage: 'Error getting available scripting languages from Elasticsearch',
})
);
return [];
return [] as estypes.ScriptLanguage[];
});

View file

@ -51,7 +51,7 @@ export const ProgressIndicator: FunctionComponent<ProgressIndicatorProps> = ({ o
} catch (error) {
const { response, body = {} } = error as IHttpFetchError;
isAvailable = response ? response.status < 500 : undefined;
isPastPreboot = isKibanaPastPreboot(response, body);
isPastPreboot = isKibanaPastPreboot(response, body as StatusResponse);
}
return isAvailable === true && isPastPreboot
? 'complete'

View file

@ -11,7 +11,7 @@ import type { FunctionComponent } from 'react';
import React from 'react';
import { FormattedMessage } from '@kbn/i18n/react';
import type { IHttpFetchError } from 'kibana/public';
import type { IHttpFetchError, ResponseErrorBody } from 'kibana/public';
import {
ERROR_CONFIGURE_FAILURE,
@ -29,7 +29,7 @@ export interface SubmitErrorCalloutProps {
}
export const SubmitErrorCallout: FunctionComponent<SubmitErrorCalloutProps> = (props) => {
const error = props.error as IHttpFetchError;
const error = props.error as IHttpFetchError<ResponseErrorBody>;
if (
error.body?.statusCode === 404 ||

View file

@ -20,7 +20,7 @@ import React from 'react';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
import type { IHttpFetchError } from 'kibana/public';
import type { IHttpFetchError, ResponseErrorBody } from 'kibana/public';
import { VERIFICATION_CODE_LENGTH } from '../common';
import { SingleCharsField } from './single_chars_field';
@ -71,7 +71,7 @@ export const VerificationCodeForm: FunctionComponent<VerificationCodeFormProps>
});
} catch (error) {
if ((error as IHttpFetchError).response?.status === 403) {
form.setError('code', (error as IHttpFetchError).body?.message);
form.setError('code', (error as IHttpFetchError<ResponseErrorBody>).body?.message || '');
return;
} else {
throw error;

View file

@ -29,7 +29,7 @@ export async function shortenUrl(
params: { url: relativeUrl },
});
const resp = await post('/api/short_url', {
const resp = await post<{ id: string }>('/api/short_url', {
body,
});

View file

@ -22,7 +22,8 @@ export function createReporter(config: AnalyicsReporterConfig): Reporter {
debug,
storage: localStorage,
async http(report) {
const response = await fetch.post('/api/ui_counters/_report', {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const response = await fetch.post<any>('/api/ui_counters/_report', {
body: JSON.stringify({ report }),
asSystemRequest: true,
});

View file

@ -25,7 +25,7 @@ interface TimelionExpressionInputProps {
}
function TimelionExpressionInput({ value, setValue }: TimelionExpressionInputProps) {
const functionList = useRef([]);
const functionList = useRef<ITimelionFunction[]>([]);
const kibana = useKibana();
const argValueSuggestions = useMemo(getArgValueSuggestions, []);
@ -84,7 +84,7 @@ function TimelionExpressionInput({ value, setValue }: TimelionExpressionInputPro
useEffect(() => {
if (kibana.services.http) {
kibana.services.http.get('../api/timelion/functions').then((data) => {
kibana.services.http.get<ITimelionFunction[]>('../api/timelion/functions').then((data) => {
functionList.current = data;
});
}

View file

@ -33,9 +33,10 @@ export default function ({ getService, getPageObjects }: PluginFunctionalProvide
description: 'какое-то странное описание',
};
const result = await coreStart.http.get('/execution_context/pass', {
context,
});
const result = await coreStart.http.get<{ ['x-opaque-id']: string }>(
'/execution_context/pass',
{ context }
);
return result['x-opaque-id'];
})

View file

@ -38,10 +38,12 @@ export const ViewAlertPage = withRouter(({ http, id }: Props) => {
useEffect(() => {
if (!alert) {
http.get(`${LEGACY_BASE_ALERT_API_PATH}/alert/${id}`).then(setAlert);
http.get<Alert | null>(`${LEGACY_BASE_ALERT_API_PATH}/alert/${id}`).then(setAlert);
}
if (!alertState) {
http.get(`${LEGACY_BASE_ALERT_API_PATH}/alert/${id}/state`).then(setAlertState);
http
.get<AlertTaskState | null>(`${LEGACY_BASE_ALERT_API_PATH}/alert/${id}/state`)
.then(setAlertState);
}
}, [alert, alertState, http, id]);

View file

@ -44,10 +44,14 @@ export const ViewPeopleInSpaceAlertPage = withRouter(({ http, id }: Props) => {
useEffect(() => {
if (!alert) {
http.get(`${LEGACY_BASE_ALERT_API_PATH}/alert/${id}`).then(setAlert);
http
.get<Alert<AlwaysFiringParams> | null>(`${LEGACY_BASE_ALERT_API_PATH}/alert/${id}`)
.then(setAlert);
}
if (!alertState) {
http.get(`${LEGACY_BASE_ALERT_API_PATH}/alert/${id}/state`).then(setAlertState);
http
.get<AlertTaskState | null>(`${LEGACY_BASE_ALERT_API_PATH}/alert/${id}/state`)
.then(setAlertState);
}
}, [alert, alertState, http, id]);

View file

@ -168,8 +168,8 @@ export function ServiceMap({
status === FETCH_STATUS.FAILURE &&
error &&
'body' in error &&
error.body.statusCode === 500 &&
error.body.message === SERVICE_MAP_TIMEOUT_ERROR
error.body?.statusCode === 500 &&
error.body?.message === SERVICE_MAP_TIMEOUT_ERROR
) {
return (
<PromptContainer>

View file

@ -7,7 +7,7 @@
import { i18n } from '@kbn/i18n';
import React, { useEffect, useMemo, useState } from 'react';
import { IHttpFetchError } from 'src/core/public';
import { IHttpFetchError, ResponseErrorBody } from 'src/core/public';
import { useKibana } from '../../../../../src/plugins/kibana_react/public';
import { useTimeRangeId } from '../context/time_range_id/use_time_range_id';
import {
@ -26,10 +26,12 @@ export enum FETCH_STATUS {
export interface FetcherResult<Data> {
data?: Data;
status: FETCH_STATUS;
error?: IHttpFetchError;
error?: IHttpFetchError<ResponseErrorBody>;
}
function getDetailsFromErrorResponse(error: IHttpFetchError) {
function getDetailsFromErrorResponse(
error: IHttpFetchError<ResponseErrorBody>
) {
const message = error.body?.message ?? error.response?.statusText;
return (
<>
@ -118,7 +120,7 @@ export function useFetcher<TReturn>(
} as FetcherResult<InferResponseType<TReturn>>);
}
} catch (e) {
const err = e as Error | IHttpFetchError;
const err = e as Error | IHttpFetchError<ResponseErrorBody>;
if (!signal.aborted) {
const errorDetails =

View file

@ -66,7 +66,7 @@ export async function callApi<T = void>(
| 'delete'
| 'patch';
const res = await http[lowercaseMethod](pathname, options);
const res = await http[lowercaseMethod]<T>(pathname, options);
if (isCachable(fetchOptions)) {
cache.set(cacheKey, res);

View file

@ -25,8 +25,8 @@ export const customElementServiceFactory: CanvasCustomElementServiceFactory = ({
create: (customElement) => http.post(apiPath, { body: JSON.stringify(customElement) }),
get: (customElementId) =>
http
.get(`${apiPath}/${customElementId}`)
.then(({ data: element }: { data: CustomElement }) => element),
.get<{ data: CustomElement }>(`${apiPath}/${customElementId}`)
.then(({ data: element }) => element),
update: (id, element) => http.put(`${apiPath}/${id}`, { body: JSON.stringify(element) }),
remove: (id) => http.delete(`${apiPath}/${id}`),
find: async (name) => {

View file

@ -63,7 +63,7 @@ export const workpadServiceFactory: CanvasWorkpadServiceFactory = ({ coreStart,
return {
get: async (id: string) => {
const workpad = await coreStart.http.get(`${getApiPath()}/${id}`);
const workpad = await coreStart.http.get<any>(`${getApiPath()}/${id}`);
return { css: DEFAULT_WORKPAD_CSS, variables: [], ...workpad };
},

View file

@ -26,7 +26,7 @@ export const setupExpressions = async ({
const loadServerFunctionWrappers = async () => {
if (!cached) {
cached = (async () => {
const serverFunctionList = await coreSetup.http.get(API_ROUTE_FUNCTIONS);
const serverFunctionList = await coreSetup.http.get<any>(API_ROUTE_FUNCTIONS);
const batchedFunction = bfetch.batchedFunction({ url: API_ROUTE_FUNCTIONS });
const { serialize } = serializeProvider(expressions.getTypes());

View file

@ -32,7 +32,7 @@ export async function createFreshStore(core: CoreSetup) {
const basePath = core.http.basePath.get();
// Retrieve server functions
const serverFunctionsResponse = await core.http.get(API_ROUTE_FUNCTIONS);
const serverFunctionsResponse = await core.http.get<Record<string, unknown>>(API_ROUTE_FUNCTIONS);
const serverFunctions = Object.values(serverFunctionsResponse);
initialState.app = {

View file

@ -30,10 +30,10 @@ import {
import { CaseConfigure } from './types';
export const fetchConnectors = async ({ signal }: ApiProps): Promise<ActionConnector[]> => {
const response = await KibanaServices.get().http.fetch(`${CASE_CONFIGURE_CONNECTORS_URL}/_find`, {
method: 'GET',
signal,
});
const response = await KibanaServices.get().http.fetch<ActionConnector[]>(
`${CASE_CONFIGURE_CONNECTORS_URL}/_find`,
{ method: 'GET', signal }
);
return response;
};
@ -97,10 +97,10 @@ export const patchCaseConfigure = async (
};
export const fetchActionTypes = async ({ signal }: ApiProps): Promise<ActionTypeConnector[]> => {
const response = await KibanaServices.get().http.fetch(getAllConnectorTypesUrl(), {
method: 'GET',
signal,
});
const response = await KibanaServices.get().http.fetch<ActionTypeConnector[]>(
getAllConnectorTypesUrl(),
{ method: 'GET', signal }
);
return convertArrayToCamelCase(response) as ActionTypeConnector[];
};

View file

@ -160,7 +160,7 @@ export const AnalyticsLogic = kea<MakeLogicType<AnalyticsValues, AnalyticsAction
};
const url = `/internal/app_search/engines/${engineName}/analytics/queries`;
const response = await http.get(url, { query });
const response = await http.get<AnalyticsData>(url, { query });
actions.onAnalyticsDataLoad(response);
} catch (e) {
flashAPIErrors(e);
@ -180,7 +180,7 @@ export const AnalyticsLogic = kea<MakeLogicType<AnalyticsValues, AnalyticsAction
};
const url = `/internal/app_search/engines/${engineName}/analytics/queries/${query}`;
const response = await http.get(url, { query: queryParams });
const response = await http.get<QueryDetails>(url, { query: queryParams });
actions.onQueryDataLoad(response);
} catch (e) {

View file

@ -86,7 +86,7 @@ export const ACTIONS_COLUMN = {
try {
const query = (item as Query).key || (item as RecentQuery).query_string || '""';
const response = await http.get(
const response = await http.get<{ id: string }>(
`/internal/app_search/engines/${engineName}/curations/find_or_create`,
{ query: { query } }
);

View file

@ -104,14 +104,17 @@ export const ApiLogsLogic = kea<MakeLogicType<ApiLogsValues, ApiLogsActions>>({
const { engineName } = EngineLogic.values;
try {
const response = await http.get(`/internal/app_search/engines/${engineName}/api_logs`, {
query: {
'page[current]': values.meta.page.current,
'filters[date][from]': getDateString(-1),
'filters[date][to]': getDateString(),
sort_direction: 'desc',
},
});
const response = await http.get<ApiLogsData>(
`/internal/app_search/engines/${engineName}/api_logs`,
{
query: {
'page[current]': values.meta.page.current,
'filters[date][from]': getDateString(-1),
'filters[date][to]': getDateString(),
sort_direction: 'desc',
},
}
);
// Manual fetches (e.g. page load, user pagination) should update the view immediately,
// while polls are stored in-state until the user manually triggers the 'Refresh' action

View file

@ -23,6 +23,7 @@ import {
CrawlerDomain,
CrawlerDomainValidationResult,
CrawlerDomainValidationResultChange,
CrawlerDomainValidationResultFromServer,
CrawlerDomainValidationStepName,
} from '../../types';
import { crawlDomainValidationToResult, crawlerDataServerToClient } from '../../utils';
@ -207,7 +208,7 @@ export const AddDomainLogic = kea<MakeLogicType<AddDomainLogicValues, AddDomainL
const route = '/internal/app_search/crawler/validate_url';
try {
const data = await http.post(route, {
const data = await http.post<CrawlerDomainValidationResultFromServer>(route, {
body: JSON.stringify({ url: values.addDomainFormInputValue.trim(), checks }),
});
const result = crawlDomainValidationToResult(data);

View file

@ -12,7 +12,14 @@ import { flashAPIErrors } from '../../../shared/flash_messages';
import { HttpLogic } from '../../../shared/http';
import { EngineLogic } from '../engine';
import { CrawlerData, CrawlerDomain, CrawlEvent, CrawlRequest, CrawlerStatus } from './types';
import {
CrawlerData,
CrawlerDomain,
CrawlEvent,
CrawlRequest,
CrawlerStatus,
CrawlerDataFromServer,
} from './types';
import { crawlerDataServerToClient } from './utils';
const POLLING_DURATION = 1000;
@ -104,7 +111,9 @@ export const CrawlerLogic = kea<MakeLogicType<CrawlerValues, CrawlerActions>>({
const { engineName } = EngineLogic.values;
try {
const response = await http.get(`/internal/app_search/engines/${engineName}/crawler`);
const response = await http.get<CrawlerDataFromServer>(
`/internal/app_search/engines/${engineName}/crawler`
);
const crawlerData = crawlerDataServerToClient(response);
actions.onReceiveCrawlerData(crawlerData);

View file

@ -13,7 +13,7 @@ import { HttpLogic } from '../../../shared/http';
import { EngineLogic } from '../engine';
import { CrawlerLogic } from './crawler_logic';
import { CrawlerDomain } from './types';
import { CrawlerDataFromServer, CrawlerDomain } from './types';
import { crawlerDataServerToClient, getDeleteDomainSuccessMessage } from './utils';
interface CrawlerOverviewActions {
@ -31,7 +31,7 @@ export const CrawlerOverviewLogic = kea<MakeLogicType<{}, CrawlerOverviewActions
const { engineName } = EngineLogic.values;
try {
const response = await http.delete(
const response = await http.delete<CrawlerDataFromServer>(
`/internal/app_search/engines/${engineName}/crawler/domains/${domain.id}`,
{
query: {

View file

@ -16,7 +16,7 @@ import { EngineLogic, generateEnginePath } from '../engine';
import { CrawlerLogic } from './crawler_logic';
import { CrawlerDomain, EntryPoint, Sitemap, CrawlRule } from './types';
import { CrawlerDomain, EntryPoint, Sitemap, CrawlRule, CrawlerDomainFromServer } from './types';
import { crawlerDomainServerToClient, getDeleteDomainSuccessMessage } from './utils';
export interface CrawlerSingleDomainValues {
@ -92,7 +92,7 @@ export const CrawlerSingleDomainLogic = kea<
const { engineName } = EngineLogic.values;
try {
const response = await http.get(
const response = await http.get<CrawlerDomainFromServer>(
`/internal/app_search/engines/${engineName}/crawler/domains/${domainId}`
);
@ -113,7 +113,7 @@ export const CrawlerSingleDomainLogic = kea<
};
try {
const response = await http.put(
const response = await http.put<CrawlerDomainFromServer>(
`/internal/app_search/engines/${engineName}/crawler/domains/${domain.id}`,
{
body: JSON.stringify(payload),

View file

@ -239,7 +239,10 @@ export const CredentialsLogic = kea<CredentialsLogicType>({
'page[current]': meta.page.current,
'page[size]': meta.page.size,
};
const response = await http.get('/internal/app_search/credentials', { query });
const response = await http.get<{ meta: Meta; results: ApiToken[] }>(
'/internal/app_search/credentials',
{ query }
);
actions.setCredentialsData(response.meta, response.results);
} catch (e) {
flashAPIErrors(e);
@ -248,7 +251,9 @@ export const CredentialsLogic = kea<CredentialsLogicType>({
fetchDetails: async () => {
try {
const { http } = HttpLogic.values;
const response = await http.get('/internal/app_search/credentials/details');
const response = await http.get<CredentialsDetails>(
'/internal/app_search/credentials/details'
);
actions.setCredentialsDetails(response);
} catch (e) {
@ -287,11 +292,13 @@ export const CredentialsLogic = kea<CredentialsLogicType>({
const body = JSON.stringify(data);
if (id) {
const response = await http.put(`/internal/app_search/credentials/${name}`, { body });
const response = await http.put<ApiToken>(`/internal/app_search/credentials/${name}`, {
body,
});
actions.onApiTokenUpdateSuccess(response);
flashSuccessToast(UPDATE_MESSAGE(name));
} else {
const response = await http.post('/internal/app_search/credentials', { body });
const response = await http.post<ApiToken>('/internal/app_search/credentials', { body });
actions.onApiTokenCreateSuccess(response);
flashSuccessToast(CREATE_MESSAGE(name));
}

View file

@ -74,7 +74,7 @@ export const SuggestionsLogic = kea<MakeLogicType<SuggestionsValues, SuggestionA
const { engineName } = EngineLogic.values;
try {
const response = await http.post(
const response = await http.post<SuggestionsAPIResponse>(
`/internal/app_search/engines/${engineName}/search_relevance_suggestions`,
{
body: JSON.stringify({

View file

@ -228,7 +228,7 @@ export const CurationLogic = kea<MakeLogicType<CurationValues, CurationActions,
const { engineName } = EngineLogic.values;
try {
const response = await http.get(
const response = await http.get<Curation>(
`/internal/app_search/engines/${engineName}/curations/${props.curationId}`,
{ query: { skip_record_analytics: 'true' } }
);
@ -248,7 +248,7 @@ export const CurationLogic = kea<MakeLogicType<CurationValues, CurationActions,
clearFlashMessages();
try {
const response = await http.put(
const response = await http.put<Curation>(
`/internal/app_search/engines/${engineName}/curations/${props.curationId}`,
{
body: JSON.stringify({

View file

@ -85,12 +85,15 @@ export const CurationsLogic = kea<MakeLogicType<CurationsValues, CurationsAction
const { engineName } = EngineLogic.values;
try {
const response = await http.get(`/internal/app_search/engines/${engineName}/curations`, {
query: {
'page[current]': meta.page.current,
'page[size]': meta.page.size,
},
});
const response = await http.get<CurationsAPIResponse>(
`/internal/app_search/engines/${engineName}/curations`,
{
query: {
'page[current]': meta.page.current,
'page[size]': meta.page.size,
},
}
);
actions.onCurationsLoad(response);
} catch (e) {
flashAPIErrors(e);
@ -118,9 +121,10 @@ export const CurationsLogic = kea<MakeLogicType<CurationsValues, CurationsAction
clearFlashMessages();
try {
const response = await http.post(`/internal/app_search/engines/${engineName}/curations`, {
body: JSON.stringify({ queries }),
});
const response = await http.post<{ id: string }>(
`/internal/app_search/engines/${engineName}/curations`,
{ body: JSON.stringify({ queries }) }
);
navigateToUrl(generateEnginePath(ENGINE_CURATION_PATH, { curationId: response.id }));
} catch (e) {
flashAPIErrors(e);

View file

@ -79,7 +79,8 @@ export const CurationSuggestionLogic = kea<
const { engineName } = EngineLogic.values;
try {
const suggestionResponse = await http.get(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const suggestionResponse = await http.get<any>(
`/internal/app_search/engines/${engineName}/search_relevance_suggestions/${props.query}`,
{
query: {

View file

@ -71,7 +71,7 @@ export const CurationsSettingsLogic = kea<
const { engineName } = EngineLogic.values;
try {
const response = await http.get(
const response = await http.get<{ curation: CurationsSettings }>(
`/internal/app_search/engines/${engineName}/search_relevance_suggestions/settings`
);
actions.onCurationsSettingsLoad(response.curation);
@ -95,7 +95,7 @@ export const CurationsSettingsLogic = kea<
const { http } = HttpLogic.values;
const { engineName } = EngineLogic.values;
try {
const response = await http.put(
const response = await http.put<{ curation: CurationsSettings }>(
`/internal/app_search/engines/${engineName}/search_relevance_suggestions/settings`,
{
body: JSON.stringify({ curation: currationsSetting }),

View file

@ -181,7 +181,10 @@ export const DocumentCreationLogic = kea<
const promises = chunk(documents, CHUNK_SIZE).map((documentsChunk) => {
const body = JSON.stringify({ documents: documentsChunk });
return http.post(`/internal/app_search/engines/${engineName}/documents`, { body });
return http.post<DocumentCreationSummary>(
`/internal/app_search/engines/${engineName}/documents`,
{ body }
);
});
try {

View file

@ -59,7 +59,7 @@ export const DocumentDetailLogic = kea<DocumentDetailLogicType>({
try {
const { http } = HttpLogic.values;
const response = await http.get(
const response = await http.get<{ fields: FieldDetails[] }>(
`/internal/app_search/engines/${engineName}/documents/${documentId}`
);
actions.setFields(response.fields);

View file

@ -132,7 +132,9 @@ export const EngineLogic = kea<MakeLogicType<EngineValues, EngineActions>>({
const { http } = HttpLogic.values;
try {
const response = await http.get(`/internal/app_search/engines/${engineName}`);
const response = await http.get<EngineDetails>(
`/internal/app_search/engines/${engineName}`
);
actions.setEngineData(response);
} catch (error) {
if (error?.response?.status >= 400 && error?.response?.status < 500) {

View file

@ -84,7 +84,9 @@ export const EngineOverviewLogic = kea<MakeLogicType<EngineOverviewValues, Engin
const { engineName } = EngineLogic.values;
try {
const response = await http.get(`/internal/app_search/engines/${engineName}/overview`);
const response = await http.get<EngineOverviewApiData>(
`/internal/app_search/engines/${engineName}/overview`
);
actions.onOverviewMetricsLoad(response);
} catch (e) {
flashAPIErrors(e);

View file

@ -119,7 +119,7 @@ export const EnginesLogic = kea<MakeLogicType<EnginesValues, EnginesActions>>({
const { enginesMeta } = values;
try {
const response = await http.get('/internal/app_search/engines', {
const response = await http.get<EnginesAPIResponse>('/internal/app_search/engines', {
query: {
type: 'indexed',
'page[current]': enginesMeta.page.current,
@ -136,7 +136,7 @@ export const EnginesLogic = kea<MakeLogicType<EnginesValues, EnginesActions>>({
const { metaEnginesMeta } = values;
try {
const response = await http.get('/internal/app_search/engines', {
const response = await http.get<EnginesAPIResponse>('/internal/app_search/engines', {
query: {
type: 'meta',
'page[current]': metaEnginesMeta.page.current,

View file

@ -246,7 +246,7 @@ export const RelevanceTuningLogic = kea<
const url = `/internal/app_search/engines/${engineName}/search_settings/details`;
try {
const response = await http.get(url);
const response = await http.get<RelevanceTuningProps>(url);
actions.onInitializeRelevanceTuning({
...response,
searchSettings: {
@ -278,7 +278,7 @@ export const RelevanceTuningLogic = kea<
const filteredBoosts = removeEmptyValueBoosts(boosts);
try {
const response = await http.post(url, {
const response = await http.post<{ results: Result[] }>(url, {
query: {
query,
},
@ -313,7 +313,7 @@ export const RelevanceTuningLogic = kea<
const url = `/internal/app_search/engines/${engineName}/search_settings`;
try {
const response = await http.put(url, {
const response = await http.put<SearchSettings>(url, {
body: JSON.stringify(removeBoostStateProps(values.searchSettings)),
});
flashSuccessToast(UPDATE_SUCCESS_MESSAGE, { text: SUCCESS_CHANGES_MESSAGE });
@ -337,7 +337,7 @@ export const RelevanceTuningLogic = kea<
const url = `/internal/app_search/engines/${engineName}/search_settings/reset`;
try {
const response = await http.post(url);
const response = await http.post<SearchSettings>(url);
flashSuccessToast(DELETE_SUCCESS_MESSAGE, { text: SUCCESS_CHANGES_MESSAGE });
actions.onSearchSettingsSuccess(response);
} catch (e) {

View file

@ -12,13 +12,14 @@ import { i18n } from '@kbn/i18n';
import { flashAPIErrors, flashSuccessToast } from '../../../shared/flash_messages';
import { HttpLogic } from '../../../shared/http';
import { Schema, SchemaConflicts } from '../../../shared/schema/types';
import { Schema, SchemaConflicts, SchemaType } from '../../../shared/schema/types';
import { EngineLogic } from '../engine';
import { DEFAULT_SNIPPET_SIZE } from './constants';
import {
FieldResultSetting,
FieldResultSettingObject,
ServerFieldResultSetting,
ServerFieldResultSettingObject,
} from './types';
@ -299,7 +300,11 @@ export const ResultSettingsLogic = kea<MakeLogicType<ResultSettingsValues, Resul
schema,
schemaConflicts,
searchSettings: { result_fields: serverFieldResultSettings },
} = await http.get(url);
} = await http.get<{
schema: Record<string, SchemaType>;
schemaConflicts?: SchemaConflicts;
searchSettings: { result_fields: Record<string, ServerFieldResultSetting> };
}>(url);
actions.initializeResultFields(serverFieldResultSettings, schema, schemaConflicts);
} catch (e) {
@ -322,7 +327,9 @@ export const ResultSettingsLogic = kea<MakeLogicType<ResultSettingsValues, Resul
actions.saving();
try {
const response = await http.put(url, {
const response = await http.put<{
result_fields: Record<string, ServerFieldResultSetting>;
}>(url, {
body: JSON.stringify({
result_fields: values.reducedServerResultFields,
}),

View file

@ -14,6 +14,7 @@ import { flashAPIErrors } from '../../../../shared/flash_messages';
import { HttpLogic } from '../../../../shared/http';
import { EngineLogic } from '../../engine';
import { FieldValue } from '../../result/types';
import { SampleSearchResponse, ServerFieldResultSettingObject } from '../types';
const NO_RESULTS_MESSAGE = i18n.translate(
@ -71,7 +72,7 @@ export const SampleResponseLogic = kea<MakeLogicType<SampleResponseValues, Sampl
const url = `/internal/app_search/engines/${engineName}/search`;
try {
const response = await http.post(url, {
const response = await http.post<{ results: Array<Record<string, FieldValue>> }>(url, {
query: { query },
body: JSON.stringify({
page: {
@ -84,6 +85,7 @@ export const SampleResponseLogic = kea<MakeLogicType<SampleResponseValues, Sampl
const result = response.results?.[0];
actions.getSearchResultsSuccess(
// @ts-expect-error TS2345
result ? { ...result, _meta: undefined } : NO_RESULTS_MESSAGE
);
} catch (e) {

View file

@ -356,7 +356,7 @@ export const RoleMappingsLogic = kea<MakeLogicType<RoleMappingsValues, RoleMappi
const route = '/internal/app_search/role_mappings/enable_role_based_access';
try {
const response = await http.post(route);
const response = await http.post<{ roleMappings: ASRoleMapping[] }>(route);
actions.setRoleMappings(response);
} catch (e) {
flashAPIErrors(e);
@ -367,7 +367,7 @@ export const RoleMappingsLogic = kea<MakeLogicType<RoleMappingsValues, RoleMappi
const route = '/internal/app_search/role_mappings';
try {
const response = await http.get(route);
const response = await http.get<RoleMappingsServerDetails>(route);
actions.setRoleMappingsData(response);
} catch (e) {
flashAPIErrors(e);
@ -466,7 +466,10 @@ export const RoleMappingsLogic = kea<MakeLogicType<RoleMappingsValues, RoleMappi
});
try {
const response = await http.post('/internal/app_search/single_user_role_mapping', { body });
const response = await http.post<UserMapping | undefined>(
'/internal/app_search/single_user_role_mapping',
{ body }
);
actions.setSingleUserRoleMapping(response);
actions.setUserCreated();
actions.initializeRoleMappings();

View file

@ -53,7 +53,7 @@ export const ReindexJobLogic = kea<MakeLogicType<ReindexJobValues, ReindexJobAct
const { engineName } = EngineLogic.values;
try {
const response = await http.get(
const response = await http.get<ReindexJobApiResponse>(
`/internal/app_search/engines/${engineName}/reindex_job/${id}`
);
actions.onLoadSuccess(response);

View file

@ -56,7 +56,9 @@ export const SchemaBaseLogic = kea<MakeLogicType<SchemaBaseValues, SchemaBaseAct
const { engineName } = EngineLogic.values;
try {
const response = await http.get(`/internal/app_search/engines/${engineName}/schema`);
const response = await http.get<SchemaApiResponse | MetaEngineSchemaApiResponse>(
`/internal/app_search/engines/${engineName}/schema`
);
actions.onSchemaLoad(response);
} catch (e) {
flashAPIErrors(e);

View file

@ -146,9 +146,10 @@ export const SchemaLogic = kea<MakeLogicType<SchemaValues, SchemaActions>>({
clearFlashMessages();
try {
const response = await http.post(`/internal/app_search/engines/${engineName}/schema`, {
body: JSON.stringify(schema),
});
const response = await http.post<SchemaApiResponse>(
`/internal/app_search/engines/${engineName}/schema`,
{ body: JSON.stringify(schema) }
);
actions.onSchemaLoad(response);
flashSuccessToast(successMessage || UPDATE_SCHEMA_SUCCESS);
} catch (e) {

View file

@ -61,9 +61,10 @@ export const SearchLogic = kea<MakeLogicType<SearchValues, SearchActions>>({
const { engineName } = EngineLogic.values;
try {
const response = await http.post(`/internal/app_search/engines/${engineName}/search`, {
query: { query },
});
const response = await http.post<{ results: Result[] }>(
`/internal/app_search/engines/${engineName}/search`,
{ query: { query } }
);
actions.onSearch(response);
} catch (e) {
flashAPIErrors(e);

View file

@ -106,7 +106,11 @@ export const SearchUILogic = kea<MakeLogicType<SearchUIValues, SearchUIActions>>
const url = `/internal/app_search/engines/${engineName}/search_ui/field_config`;
try {
const initialFieldValues = await http.get(url);
const initialFieldValues = await http.get<
InitialFieldValues & {
defaultValues: Pick<InitialFieldValues, 'urlField' | 'titleField'>;
}
>(url);
const {
defaultValues: { urlField, titleField },
validFields,

View file

@ -115,12 +115,15 @@ export const SynonymsLogic = kea<MakeLogicType<SynonymsValues, SynonymsActions>>
const { engineName } = EngineLogic.values;
try {
const response = await http.get(`/internal/app_search/engines/${engineName}/synonyms`, {
query: {
'page[current]': meta.page.current,
'page[size]': meta.page.size,
},
});
const response = await http.get<SynonymsApiResponse>(
`/internal/app_search/engines/${engineName}/synonyms`,
{
query: {
'page[current]': meta.page.current,
'page[size]': meta.page.size,
},
}
);
actions.onSynonymsLoad(response);
} catch (e) {
flashAPIErrors(e);

View file

@ -83,7 +83,9 @@ export const GenericEndpointInlineEditableTableLogic = kea<
const { addRoute, onAdd, dataProperty } = props;
try {
const response = await http.post(addRoute, { body: JSON.stringify(item) });
const response = await http.post<Record<string, ItemWithAnID[]>>(addRoute, {
body: JSON.stringify(item),
});
const itemsFromResponse = response[dataProperty];
onAdd(item, itemsFromResponse);
@ -99,7 +101,7 @@ export const GenericEndpointInlineEditableTableLogic = kea<
const { deleteRoute, onDelete, dataProperty } = props;
try {
const response = await http.delete(deleteRoute(item));
const response = await http.delete<Record<string, ItemWithAnID[]>>(deleteRoute(item));
const itemsFromResponse = response[dataProperty];
onDelete(item, itemsFromResponse);
@ -116,7 +118,7 @@ export const GenericEndpointInlineEditableTableLogic = kea<
const dataToSubmit = stripIdAndCreatedAtFromItem(item);
try {
const response = await http.put(updateRoute(item), {
const response = await http.put<Record<string, ItemWithAnID[]>>(updateRoute(item), {
body: JSON.stringify(dataToSubmit),
});
const itemsFromResponse = response[dataProperty];
@ -141,7 +143,7 @@ export const GenericEndpointInlineEditableTableLogic = kea<
try {
actions.setLoading();
const response = await http.put(reorderRoute, {
const response = await http.put<Record<string, ItemWithAnID[]>>(reorderRoute, {
body: JSON.stringify({ [dataProperty]: reorderedItemIds }),
});
const itemsFromResponse = response[dataProperty];

View file

@ -392,7 +392,7 @@ export const AddSourceLogic = kea<MakeLogicType<AddSourceValues, AddSourceAction
const route = `/internal/workplace_search/org/settings/connectors/${serviceType}`;
try {
const response = await HttpLogic.values.http.get(route);
const response = await HttpLogic.values.http.get<SourceConfigData>(route);
actions.setSourceConfigData(response);
} catch (e) {
flashAPIErrors(e);
@ -415,7 +415,7 @@ export const AddSourceLogic = kea<MakeLogicType<AddSourceValues, AddSourceAction
if (subdomain) query.subdomain = subdomain;
try {
const response = await HttpLogic.values.http.get(route, { query });
const response = await HttpLogic.values.http.get<SourceConnectData>(route, { query });
actions.setSourceConnectData(response);
successCallback(response.oauthUrl);
} catch (e) {
@ -435,7 +435,7 @@ export const AddSourceLogic = kea<MakeLogicType<AddSourceValues, AddSourceAction
} as HttpFetchQuery;
try {
const response = await HttpLogic.values.http.get(route, { query });
const response = await HttpLogic.values.http.get<SourceConnectData>(route, { query });
actions.setSourceConnectData(response);
} catch (e) {
flashAPIErrors(e);
@ -449,7 +449,7 @@ export const AddSourceLogic = kea<MakeLogicType<AddSourceValues, AddSourceAction
: `/internal/workplace_search/account/pre_sources/${preContentSourceId}`;
try {
const response = await HttpLogic.values.http.get(route);
const response = await HttpLogic.values.http.get<PreContentSourceResponse>(route);
actions.setPreContentSourceConfigData(response);
} catch (e) {
flashAPIErrors(e);
@ -482,7 +482,7 @@ export const AddSourceLogic = kea<MakeLogicType<AddSourceValues, AddSourceAction
};
try {
const response = await http(route, {
const response = await http<SourceConfigData>(route, {
body: JSON.stringify(params),
});
if (successCallback) successCallback();
@ -527,7 +527,13 @@ export const AddSourceLogic = kea<MakeLogicType<AddSourceValues, AddSourceAction
}
try {
const response = await http.get(route, { query });
const response = await http.get<{
serviceName: string;
indexPermissions: boolean;
serviceType: string;
preContentSourceId: string;
hasConfigureStep: boolean;
}>(route, { query });
const { serviceName, indexPermissions, serviceType, preContentSourceId, hasConfigureStep } =
response;
@ -574,7 +580,7 @@ export const AddSourceLogic = kea<MakeLogicType<AddSourceValues, AddSourceAction
Object.keys(params).forEach((key) => params[key] === undefined && delete params[key]);
try {
const response = await HttpLogic.values.http.post(route, {
const response = await HttpLogic.values.http.post<CustomSource>(route, {
body: JSON.stringify({ ...params }),
});
actions.setCustomSourceData(response);

View file

@ -381,8 +381,10 @@ export const DisplaySettingsLogic = kea<
: `/internal/workplace_search/account/sources/${sourceId}/display_settings/config`;
try {
const response = await HttpLogic.values.http.get(route);
const response = await HttpLogic.values.http.get<DisplaySettingsResponseProps>(route);
actions.onInitializeDisplaySettings({
// isOrganization is not typed
// @ts-expect-error TS2345
isOrganization,
sourceId,
serverRoute: route,
@ -396,9 +398,10 @@ export const DisplaySettingsLogic = kea<
const { searchResultConfig, serverRoute } = values;
try {
const response = await HttpLogic.values.http.post(serverRoute, {
body: JSON.stringify({ ...searchResultConfig }),
});
const response = await HttpLogic.values.http.post<DisplaySettingsResponseProps>(
serverRoute,
{ body: JSON.stringify({ ...searchResultConfig }) }
);
actions.setServerResponseData(response);
} catch (e) {
flashAPIErrors(e);

View file

@ -272,7 +272,9 @@ export const SchemaLogic = kea<MakeLogicType<SchemaValues, SchemaActions>>({
: `/internal/workplace_search/account/sources/${sourceId}/schemas`;
try {
const response = await http.get(route);
const response = await http.get<SchemaInitialData>(route);
// TODO: fix
// @ts-expect-error TS2783
actions.onInitializeSchema({ sourceId, ...response });
} catch (e) {
flashAPIErrors(e);
@ -287,7 +289,7 @@ export const SchemaLogic = kea<MakeLogicType<SchemaValues, SchemaActions>>({
try {
await actions.initializeSchema();
const response = await http.get(route);
const response = await http.get<SchemaChangeErrorsProps>(route);
actions.onInitializeSchemaFieldErrors({
fieldCoercionErrors: response.fieldCoercionErrors,
});
@ -339,7 +341,7 @@ export const SchemaLogic = kea<MakeLogicType<SchemaValues, SchemaActions>>({
actions.resetMostRecentIndexJob(emptyReindexJob);
try {
const response = await http.post(route, {
const response = await http.post<SchemaResponseProps>(route, {
body: JSON.stringify({ ...updatedSchema }),
});
actions.onSchemaSetSuccess(response);

View file

@ -20,10 +20,12 @@ import {
BLOCKED_TIME_WINDOWS_PATH,
getContentSourcePath,
} from '../../../../routes';
import {
BlockedWindow,
DayOfWeek,
IndexingSchedule,
ContentSourceFullData,
SyncJobType,
TimeUnit,
} from '../../../../types';
@ -313,7 +315,7 @@ export const SynchronizationLogic = kea<
const route = `/internal/workplace_search/org/sources/${sourceId}/settings`;
try {
const response = await HttpLogic.values.http.patch(route, {
const response = await HttpLogic.values.http.patch<ContentSourceFullData>(route, {
body: JSON.stringify(body),
});

View file

@ -159,7 +159,9 @@ export const SourceLogic = kea<MakeLogicType<SourceValues, SourceActions>>({
: `/internal/workplace_search/account/sources/${sourceId}`;
try {
const response = await HttpLogic.values.http.get(route);
const response = await HttpLogic.values.http.get<
ContentSourceFullData & { errors?: string }
>(route);
actions.setContentSource(response);
if (response.isFederatedSource) {
actions.initializeFederatedSummary(sourceId);
@ -186,7 +188,7 @@ export const SourceLogic = kea<MakeLogicType<SourceValues, SourceActions>>({
initializeFederatedSummary: async ({ sourceId }) => {
const route = `/internal/workplace_search/account/sources/${sourceId}/federated_summary`;
try {
const response = await HttpLogic.values.http.get(route);
const response = await HttpLogic.values.http.get<{ summary: DocumentSummaryItem[] }>(route);
actions.onUpdateSummary(response.summary);
} catch (e) {
flashAPIErrors(e);
@ -206,7 +208,7 @@ export const SourceLogic = kea<MakeLogicType<SourceValues, SourceActions>>({
} = values;
try {
const response = await HttpLogic.values.http.post(route, {
const response = await HttpLogic.values.http.post<SearchResultsResponse>(route, {
body: JSON.stringify({ query, page }),
});
actions.setSearchResults(response);
@ -221,7 +223,7 @@ export const SourceLogic = kea<MakeLogicType<SourceValues, SourceActions>>({
: `/internal/workplace_search/account/sources/${sourceId}/settings`;
try {
const response = await HttpLogic.values.http.patch(route, {
const response = await HttpLogic.values.http.patch<{ name: string }>(route, {
body: JSON.stringify({ content_source: source }),
});
if (source.name) {
@ -239,7 +241,7 @@ export const SourceLogic = kea<MakeLogicType<SourceValues, SourceActions>>({
: `/internal/workplace_search/account/sources/${sourceId}`;
try {
const response = await HttpLogic.values.http.delete(route);
const response = await HttpLogic.values.http.delete<{ name: string }>(route);
KibanaLogic.values.navigateToUrl(getSourcesPath(SOURCES_PATH, isOrganization));
flashSuccessToast(
i18n.translate(

View file

@ -163,7 +163,7 @@ export const SourcesLogic = kea<MakeLogicType<ISourcesValues, ISourcesActions>>(
: '/internal/workplace_search/account/sources';
try {
const response = await HttpLogic.values.http.get(route);
const response = await HttpLogic.values.http.get<ISourcesServerResponse>(route);
breakpoint(); // Prevents errors if logic unmounts while fetching
actions.pollForSourceStatusChanges();
actions.onInitializeSources(response);
@ -256,7 +256,7 @@ export const fetchSourceStatuses = async (
let response;
try {
response = await HttpLogic.values.http.get(route);
response = await HttpLogic.values.http.get<ContentSourceStatus[]>(route);
breakpoint();
SourcesLogic.actions.setServerSourceStatuses(response);
} catch (e) {
@ -267,7 +267,8 @@ export const fetchSourceStatuses = async (
}
}
return response;
// TODO: remove casting. return type should be ContentSourceStatus[] | undefined
return response as ContentSourceStatus[];
};
const updateSourcesOnToggle = (

View file

@ -174,7 +174,7 @@ export const GroupLogic = kea<MakeLogicType<GroupValues, GroupActions>>({
listeners: ({ actions, values }) => ({
initializeGroup: async ({ groupId }) => {
try {
const response = await HttpLogic.values.http.get(
const response = await HttpLogic.values.http.get<GroupDetails>(
`/internal/workplace_search/groups/${groupId}`
);
actions.onInitializeGroup(response);
@ -220,7 +220,7 @@ export const GroupLogic = kea<MakeLogicType<GroupValues, GroupActions>>({
} = values;
try {
const response = await HttpLogic.values.http.put(
const response = await HttpLogic.values.http.put<GroupDetails>(
`/internal/workplace_search/groups/${id}`,
{
body: JSON.stringify({ group: { name: groupNameInputValue } }),
@ -247,7 +247,7 @@ export const GroupLogic = kea<MakeLogicType<GroupValues, GroupActions>>({
} = values;
try {
const response = await HttpLogic.values.http.post(
const response = await HttpLogic.values.http.post<GroupDetails>(
`/internal/workplace_search/groups/${id}/share`,
{
body: JSON.stringify({ content_source_ids: selectedGroupSources }),
@ -279,7 +279,7 @@ export const GroupLogic = kea<MakeLogicType<GroupValues, GroupActions>>({
);
try {
const response = await HttpLogic.values.http.put(
const response = await HttpLogic.values.http.put<GroupDetails>(
`/internal/workplace_search/groups/${id}/boosts`,
{
body: JSON.stringify({ content_source_boosts: boosts }),

View file

@ -255,7 +255,9 @@ export const GroupsLogic = kea<MakeLogicType<GroupsValues, GroupsActions>>({
listeners: ({ actions, values }) => ({
initializeGroups: async () => {
try {
const response = await HttpLogic.values.http.get('/internal/workplace_search/groups');
const response = await HttpLogic.values.http.get<GroupsServerData>(
'/internal/workplace_search/groups'
);
actions.onInitializeGroups(response);
} catch (e) {
flashAPIErrors(e);
@ -288,7 +290,7 @@ export const GroupsLogic = kea<MakeLogicType<GroupsValues, GroupsActions>>({
};
try {
const response = await HttpLogic.values.http.post(
const response = await HttpLogic.values.http.post<GroupsSearchResponse>(
'/internal/workplace_search/groups/search',
{
body: JSON.stringify({
@ -307,7 +309,7 @@ export const GroupsLogic = kea<MakeLogicType<GroupsValues, GroupsActions>>({
fetchGroupUsers: async ({ groupId }) => {
actions.setAllGroupLoading(true);
try {
const response = await HttpLogic.values.http.get(
const response = await HttpLogic.values.http.get<User[]>(
`/internal/workplace_search/groups/${groupId}/group_users`
);
actions.setGroupUsers(response);
@ -317,10 +319,13 @@ export const GroupsLogic = kea<MakeLogicType<GroupsValues, GroupsActions>>({
},
saveNewGroup: async () => {
try {
const response = await HttpLogic.values.http.post('/internal/workplace_search/groups', {
body: JSON.stringify({ group_name: values.newGroupName }),
headers,
});
const response = await HttpLogic.values.http.post<Group>(
'/internal/workplace_search/groups',
{
body: JSON.stringify({ group_name: values.newGroupName }),
headers,
}
);
actions.getSearchResults(true);
const SUCCESS_MESSAGE = i18n.translate(

View file

@ -96,7 +96,7 @@ export const OAuthAuthorizeLogic = kea<MakeLogicType<OAuthAuthorizeValues, OAuth
const query = parseQueryParams(queryString);
try {
const response = await http.get(oauthAuthorizeRoute, { query });
const response = await http.get<OAuthPreAuthServerProps>(oauthAuthorizeRoute, { query });
if (response.status === 'redirect') {
window.location.replace(response.redirect_uri);
@ -113,7 +113,7 @@ export const OAuthAuthorizeLogic = kea<MakeLogicType<OAuthAuthorizeValues, OAuth
const { cachedPreAuth } = values;
try {
const response = await http.delete(oauthAuthorizeRoute, {
const response = await http.delete<{ redirect_uri: string }>(oauthAuthorizeRoute, {
body: JSON.stringify({
client_id: cachedPreAuth.clientId,
response_type: cachedPreAuth.responseType,
@ -135,7 +135,7 @@ export const OAuthAuthorizeLogic = kea<MakeLogicType<OAuthAuthorizeValues, OAuth
const { cachedPreAuth } = values;
try {
const response = await http.post(oauthAuthorizeRoute, {
const response = await http.post<{ redirect_uri: string }>(oauthAuthorizeRoute, {
body: JSON.stringify({
client_id: cachedPreAuth.clientId,
response_type: cachedPreAuth.responseType,

View file

@ -97,7 +97,9 @@ export const OverviewLogic = kea<MakeLogicType<OverviewValues, OverviewActions>>
listeners: ({ actions }) => ({
initializeOverview: async () => {
try {
const response = await HttpLogic.values.http.get('/internal/workplace_search/overview');
const response = await HttpLogic.values.http.get<OverviewServerData>(
'/internal/workplace_search/overview'
);
actions.setServerData(response);
} catch (e) {
flashAPIErrors(e);

View file

@ -356,7 +356,9 @@ export const RoleMappingsLogic = kea<MakeLogicType<RoleMappingsValues, RoleMappi
const route = '/internal/workplace_search/org/role_mappings/enable_role_based_access';
try {
const response = await http.post(route);
const response = await http.post<{
roleMappings: WSRoleMapping[];
}>(route);
actions.setRoleMappings(response);
} catch (e) {
flashAPIErrors(e);
@ -367,7 +369,7 @@ export const RoleMappingsLogic = kea<MakeLogicType<RoleMappingsValues, RoleMappi
const route = '/internal/workplace_search/org/role_mappings';
try {
const response = await http.get(route);
const response = await http.get<RoleMappingsServerDetails>(route);
actions.setRoleMappingsData(response);
} catch (e) {
flashAPIErrors(e);
@ -466,11 +468,9 @@ export const RoleMappingsLogic = kea<MakeLogicType<RoleMappingsValues, RoleMappi
});
try {
const response = await http.post(
const response = await http.post<UserMapping>(
'/internal/workplace_search/org/single_user_role_mapping',
{
body,
}
{ body }
);
actions.setSingleUserRoleMapping(response);
actions.setUserCreated();

View file

@ -71,7 +71,7 @@ export const SearchAuthorizeLogic = kea<
};
try {
const response = await http.get(oauthAuthorizeRoute, { query });
const response = await http.get<OAuthPreAuthServerProps>(oauthAuthorizeRoute, { query });
if (response.status === 'redirect') {
window.location.replace(response.redirect_uri);
@ -91,7 +91,7 @@ export const SearchAuthorizeLogic = kea<
const { cachedPreAuth } = values;
try {
const response = await http.post(oauthAuthorizeRoute, {
const response = await http.post<{ redirect_uri: string }>(oauthAuthorizeRoute, {
body: JSON.stringify({
client_id: cachedPreAuth.clientId,
response_type: cachedPreAuth.responseType,

View file

@ -138,7 +138,7 @@ export const SecurityLogic = kea<MakeLogicType<SecurityValues, SecurityActions>>
const { http } = HttpLogic.values;
try {
const response = await http.get(route);
const response = await http.get<SecurityServerProps>(route);
actions.setServerProps(response);
} catch (e) {
flashAPIErrors(e);
@ -151,7 +151,7 @@ export const SecurityLogic = kea<MakeLogicType<SecurityValues, SecurityActions>>
const { http } = HttpLogic.values;
try {
const response = await http.patch(route, { body });
const response = await http.patch<SecurityServerProps>(route, { body });
actions.setSourceRestrictionsUpdated(response);
flashSuccessToast(SOURCE_RESTRICTIONS_SUCCESS_MESSAGE);
AppLogic.actions.setSourceRestriction(isEnabled);

View file

@ -200,7 +200,7 @@ export const SettingsLogic = kea<MakeLogicType<SettingsValues, SettingsActions>>
const route = '/internal/workplace_search/org/settings';
try {
const response = await http.get(route);
const response = await http.get<SettingsServerProps>(route);
actions.setServerProps(response);
} catch (e) {
flashAPIErrors(e);
@ -211,7 +211,7 @@ export const SettingsLogic = kea<MakeLogicType<SettingsValues, SettingsActions>>
const route = '/internal/workplace_search/org/settings/connectors';
try {
const response = await http.get(route);
const response = await http.get<Connector[]>(route);
actions.onInitializeConnectors(response);
} catch (e) {
flashAPIErrors(e);
@ -225,7 +225,9 @@ export const SettingsLogic = kea<MakeLogicType<SettingsValues, SettingsActions>>
const body = JSON.stringify({ name });
try {
const response = await http.put(route, { body });
const response = await http.put<{
organizationName: string;
}>(route, { body });
actions.setUpdatedName(response);
flashSuccessToast(ORG_UPDATED_MESSAGE);
AppLogic.actions.setOrgName(name);
@ -240,7 +242,7 @@ export const SettingsLogic = kea<MakeLogicType<SettingsValues, SettingsActions>>
const body = JSON.stringify({ logo });
try {
const response = await http.put(imageRoute, { body });
const response = await http.put<{ logo: string | null }>(imageRoute, { body });
actions.setLogo(response.logo);
flashSuccessToast(ORG_UPDATED_MESSAGE);
} catch (e) {
@ -255,7 +257,7 @@ export const SettingsLogic = kea<MakeLogicType<SettingsValues, SettingsActions>>
const body = JSON.stringify({ icon });
try {
const response = await http.put(imageRoute, { body });
const response = await http.put<{ icon: string | null }>(imageRoute, { body });
actions.setIcon(response.icon);
flashSuccessToast(ORG_UPDATED_MESSAGE);
} catch (e) {
@ -275,7 +277,9 @@ export const SettingsLogic = kea<MakeLogicType<SettingsValues, SettingsActions>>
clearFlashMessages();
try {
const response = await http.put(route, { body });
const response = await http.put<{
oauthApplication: IOauthApplication;
}>(route, { body });
actions.setUpdatedOauthApplication(response);
flashSuccessToast(OAUTH_APP_UPDATED_MESSAGE);
} catch (e) {

View file

@ -6,9 +6,11 @@
*/
import { i18n } from '@kbn/i18n';
import { IHttpFetchError } from 'kibana/public';
import { IHttpFetchError, ResponseErrorBody } from 'kibana/public';
export function formatHttpError(error: IHttpFetchError) {
export function formatHttpError(
error: IHttpFetchError<ResponseErrorBody & { status: number; statusText: string }>
) {
if (!error.response) {
return i18n.translate('xpack.graph.fatalError.unavailableServerErrorMessage', {
defaultMessage:
@ -20,9 +22,9 @@ export function formatHttpError(error: IHttpFetchError) {
return i18n.translate('xpack.graph.fatalError.errorStatusMessage', {
defaultMessage: 'Error {errStatus} {errStatusText}: {errMessage}',
values: {
errStatus: error.body.status,
errStatusText: error.body.statusText,
errMessage: error.body.message,
errStatus: error.body?.status,
errStatusText: error.body?.statusText,
errMessage: error.body?.message,
},
});
}

View file

@ -7,7 +7,7 @@
import { useCallback, useState } from 'react';
import { ToastsStart } from 'kibana/public';
import { IHttpFetchError, CoreStart } from 'kibana/public';
import { IHttpFetchError, ResponseErrorBody, CoreStart } from 'kibana/public';
import { i18n } from '@kbn/i18n';
import { ExploreRequest, GraphExploreCallback, GraphSearchCallback, SearchRequest } from '../types';
import { formatHttpError } from './format_http_error';
@ -21,7 +21,7 @@ export const useGraphLoader = ({ toastNotifications, coreStart }: UseGraphLoader
const [loading, setLoading] = useState(false);
const handleHttpError = useCallback(
(error: IHttpFetchError) => {
(error: IHttpFetchError<ResponseErrorBody & { status: number; statusText: string }>) => {
toastNotifications.addDanger(formatHttpError(error));
},
[toastNotifications]
@ -59,10 +59,10 @@ export const useGraphLoader = ({ toastNotifications, coreStart }: UseGraphLoader
};
setLoading(true);
return coreStart.http
.post('../api/graph/graphExplore', request)
.post<{ resp: { timed_out: unknown } }>('../api/graph/graphExplore', request)
.then(function (data) {
const response = data.resp;
if (response.timed_out) {
if (response?.timed_out) {
toastNotifications.addWarning(
i18n.translate('xpack.graph.exploreGraph.timedOutWarningText', {
defaultMessage: 'Exploration timed out',
@ -88,7 +88,7 @@ export const useGraphLoader = ({ toastNotifications, coreStart }: UseGraphLoader
};
setLoading(true);
coreStart.http
.post('../api/graph/searchProxy', request)
.post<{ resp: unknown }>('../api/graph/searchProxy', request)
.then(function (data) {
const response = data.resp;
responseHandler(response);

View file

@ -96,8 +96,8 @@ export async function fetchTopNodes(
.reduce((allAggs, subAgg) => ({ ...allAggs, ...subAgg }));
const body = createSamplerSearchBody(aggs);
const response: TopTermsAggResponse = (
await post('../api/graph/searchProxy', {
const response = (
await post<{ resp: TopTermsAggResponse }>('../api/graph/searchProxy', {
body: JSON.stringify({ index, body }),
})
).resp;

View file

@ -5,10 +5,15 @@
* 2.0.
*/
import { IHttpFetchError } from 'src/core/public';
import { IHttpFetchError, ResponseErrorBody } from 'src/core/public';
import { fatalErrors, toasts } from './notification';
function createToastConfig(error: IHttpFetchError, errorTitle: string) {
interface CommonErrorBody extends ResponseErrorBody {
error: string;
attributes: { causes: unknown[] };
}
function createToastConfig(error: IHttpFetchError<CommonErrorBody>, errorTitle: string) {
if (error && error.body) {
// Error body shape is defined by the API.
const { error: errorString, statusCode, message: errorMessage, attributes } = error.body;
@ -23,7 +28,7 @@ function createToastConfig(error: IHttpFetchError, errorTitle: string) {
}
}
export function showApiWarning(error: IHttpFetchError, errorTitle: string) {
export function showApiWarning(error: IHttpFetchError<CommonErrorBody>, errorTitle: string) {
const toastConfig = createToastConfig(error, errorTitle);
if (toastConfig) {
@ -35,7 +40,7 @@ export function showApiWarning(error: IHttpFetchError, errorTitle: string) {
return fatalErrors.add(error, errorTitle);
}
export function showApiError(error: IHttpFetchError, errorTitle: string) {
export function showApiError(error: IHttpFetchError<CommonErrorBody>, errorTitle: string) {
const toastConfig = createToastConfig(error, errorTitle);
if (toastConfig) {

View file

@ -76,7 +76,7 @@ export async function deleteDataStreams(dataStreams: string[]) {
}
export async function loadIndices() {
const response = await httpService.httpClient.get(`${API_BASE_PATH}/indices`);
const response = await httpService.httpClient.get<any>(`${API_BASE_PATH}/indices`);
return response.data ? response.data : response;
}
@ -87,7 +87,7 @@ export async function reloadIndices(
const body = JSON.stringify({
indexNames,
});
const response = await httpService.httpClient.post(`${API_BASE_PATH}/indices/reload`, {
const response = await httpService.httpClient.post<any>(`${API_BASE_PATH}/indices/reload`, {
body,
asSystemRequest,
});

View file

@ -24,7 +24,7 @@ export const useHostIpToName = (ipAddress: string | null, indexPattern: string |
throw new Error('HTTP service is unavailable');
}
if (ipAddress && indexPattern) {
const response = await fetch('/api/infra/ip_to_host', {
const response = await fetch<IpToHostResponse>('/api/infra/ip_to_host', {
method: 'POST',
body: JSON.stringify({
ip: ipAddress,

View file

@ -165,7 +165,7 @@ export const InnerFieldItem = function InnerFieldItem(props: FieldItemProps) {
setState((s) => ({ ...s, isLoading: true }));
core.http
.post(`/api/lens/index_stats/${indexPattern.id}/field`, {
.post<FieldStatsResponse<string | number>>(`/api/lens/index_stats/${indexPattern.id}/field`, {
body: JSON.stringify({
dslQuery: esQuery.buildEsQuery(
indexPattern,
@ -178,7 +178,7 @@ export const InnerFieldItem = function InnerFieldItem(props: FieldItemProps) {
fieldName: field.name,
}),
})
.then((results: FieldStatsResponse<string | number>) => {
.then((results) => {
setState((s) => ({
...s,
isLoading: false,

View file

@ -14,6 +14,7 @@ import { createLicenseUpdate } from '../common/license_update';
import { License } from '../common/license';
import { mountExpiredBanner } from './expired_banner';
import { FeatureUsageService } from './services';
import type { PublicLicenseJSON } from '../common/types';
export const licensingSessionStorageKey = 'xpack.licensing';
@ -148,9 +149,9 @@ export class LicensingPlugin implements Plugin<LicensingPluginSetup, LicensingPl
}
}
private fetchLicense = async (core: CoreSetup): Promise<ILicense> => {
private fetchLicense = async (core: CoreSetup): Promise<License> => {
try {
const response = await core.http.get({
const response = await core.http.get<PublicLicenseJSON>({
path: this.infoEndpoint,
asSystemRequest: true,
});

View file

@ -460,14 +460,13 @@ export class ESSearchSource extends AbstractESSource implements ITiledSingleLaye
if (!(this.indexPattern && this.indexPattern.title)) {
return [];
}
let success;
let matchingIndexes;
try {
({ success, matchingIndexes } = await getMatchingIndexes(this.indexPattern.title));
const { success, matchingIndexes } = await getMatchingIndexes(this.indexPattern.title);
return success ? matchingIndexes : [];
} catch (e) {
// Fail silently
return [];
}
return success ? matchingIndexes : [];
}
async supportsFeatureEditing(): Promise<boolean> {

View file

@ -42,7 +42,10 @@ export const deleteFeatureFromIndex = async (indexName: string, featureId: strin
};
export const getMatchingIndexes = async (indexPattern: string) => {
return await getHttp().fetch({
return await getHttp().fetch<{
success: boolean;
matchingIndexes: string[];
}>({
path: GET_MATCHING_INDEXES_PATH,
method: 'GET',
query: { indexPattern },
@ -50,7 +53,10 @@ export const getMatchingIndexes = async (indexPattern: string) => {
};
export const getIsDrawLayer = async (index: string) => {
return await getHttp().fetch({
return await getHttp().fetch<{
success: boolean;
isDrawingIndex: boolean;
}>({
path: CHECK_IS_DRAWING_INDEX,
method: 'GET',
query: { index },

View file

@ -5,8 +5,8 @@
* 2.0.
*/
import { useKibana } from '../../../../../../src/plugins/kibana_react/public';
import { showAlertsToast } from '../../alerts/lib/alerts_toast';
import { useRequestErrorHandler } from './use_request_error_handler';
import { EnableAlertResponse, showAlertsToast } from '../../alerts/lib/alerts_toast';
export const useAlertsModal = () => {
const { services } = useKibana();
@ -29,7 +29,14 @@ export const useAlertsModal = () => {
async function enableAlerts() {
try {
const response = await services.http?.post('../api/monitoring/v1/alerts/enable', {});
if (!services.http?.post) {
throw new Error('HTTP service is unavailable');
}
const response = await services.http.post<EnableAlertResponse>(
'../api/monitoring/v1/alerts/enable',
{}
)!;
window.localStorage.setItem('ALERTS_MODAL_DECISION_MADE', 'true');
showAlertsToast(response);
} catch (err) {

View file

@ -7,14 +7,14 @@
import React, { useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import { includes } from 'lodash';
import { IHttpFetchError } from 'kibana/public';
import { IHttpFetchError, ResponseErrorBody } from 'kibana/public';
import { FormattedMessage } from '@kbn/i18n/react';
import { EuiButton, EuiSpacer, EuiText } from '@elastic/eui';
import { formatMsg } from '../../../../../../src/plugins/kibana_legacy/public';
import { toMountPoint, useKibana } from '../../../../../../src/plugins/kibana_react/public';
import { MonitoringStartPluginDependencies } from '../../types';
export function formatMonitoringError(err: IHttpFetchError) {
export function formatMonitoringError(err: IHttpFetchError<ResponseErrorBody>) {
if (err.response?.status && err.response?.status !== -1) {
return (
<EuiText>
@ -37,7 +37,7 @@ export const useRequestErrorHandler = () => {
const { services } = useKibana<MonitoringStartPluginDependencies>();
const history = useHistory();
return useCallback(
(err: IHttpFetchError) => {
(err: IHttpFetchError<ResponseErrorBody>) => {
if (err.response?.status === 403) {
// redirect to error message view
history.push('/access-denied');

View file

@ -59,7 +59,7 @@ export const ApmInstancePage: React.FC<ComponentProps> = ({ clusters }) => {
const getPageData = useCallback(async () => {
const bounds = services.data?.query.timefilter.timefilter.getBounds();
const url = `../api/monitoring/v1/clusters/${clusterUuid}/apm/${instance}`;
const response = await services.http?.fetch(url, {
const response = await services.http?.fetch<{ apmSummary: { name: string } }>(url, {
method: 'POST',
body: JSON.stringify({
ccs,
@ -71,7 +71,7 @@ export const ApmInstancePage: React.FC<ComponentProps> = ({ clusters }) => {
});
setData(response);
setInstanceName(response.apmSummary.name);
setInstanceName(response?.apmSummary.name || '');
}, [ccs, clusterUuid, instance, services.data?.query.timefilter.timefilter, services.http]);
return (

View file

@ -60,7 +60,7 @@ export const ApmInstancesPage: React.FC<ComponentProps> = ({ clusters }) => {
const getPageData = useCallback(async () => {
const bounds = services.data?.query.timefilter.timefilter.getBounds();
const url = `../api/monitoring/v1/clusters/${clusterUuid}/apm/instances`;
const response = await services.http?.fetch(url, {
const response = await services.http?.fetch<{ stats: { total: number } }>(url, {
method: 'POST',
body: JSON.stringify({
ccs,
@ -72,7 +72,7 @@ export const ApmInstancesPage: React.FC<ComponentProps> = ({ clusters }) => {
});
setData(response);
updateTotalItemCount(response.stats.total);
updateTotalItemCount(response?.stats.total);
}, [
ccs,
clusterUuid,

View file

@ -50,7 +50,7 @@ export const ApmOverviewPage: React.FC<ComponentProps> = ({ clusters }) => {
const bounds = services.data?.query.timefilter.timefilter.getBounds();
const url = `../api/monitoring/v1/clusters/${clusterUuid}/apm`;
const response = await services.http?.fetch(url, {
const response = await services.http?.fetch<any>(url, {
method: 'POST',
body: JSON.stringify({
ccs,

View file

@ -59,7 +59,7 @@ export const BeatsInstancePage: React.FC<ComponentProps> = ({ clusters }) => {
const getPageData = useCallback(async () => {
const bounds = services.data?.query.timefilter.timefilter.getBounds();
const url = `../api/monitoring/v1/clusters/${clusterUuid}/beats/beat/${instance}`;
const response = await services.http?.fetch(url, {
const response = await services.http?.fetch<{ summary: { name: string } }>(url, {
method: 'POST',
body: JSON.stringify({
ccs,
@ -71,7 +71,7 @@ export const BeatsInstancePage: React.FC<ComponentProps> = ({ clusters }) => {
});
setData(response);
setBeatName(response.summary.name);
setBeatName(response?.summary.name || '');
}, [ccs, clusterUuid, instance, services.data?.query.timefilter.timefilter, services.http]);
return (

View file

@ -49,7 +49,7 @@ export const BeatsInstancesPage: React.FC<ComponentProps> = ({ clusters }) => {
const getPageData = useCallback(async () => {
const bounds = services.data?.query.timefilter.timefilter.getBounds();
const url = `../api/monitoring/v1/clusters/${clusterUuid}/beats/beats`;
const response = await services.http?.fetch(url, {
const response = await services.http?.fetch<{ stats: { total: number } }>(url, {
method: 'POST',
body: JSON.stringify({
ccs,
@ -61,7 +61,7 @@ export const BeatsInstancesPage: React.FC<ComponentProps> = ({ clusters }) => {
});
setData(response);
updateTotalItemCount(response.stats.total);
updateTotalItemCount(response?.stats.total);
}, [
ccs,
clusterUuid,

Some files were not shown because too many files have changed in this diff Show more