diff --git a/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md b/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md
index f6190fb3bc055..9a04a1d581765 100644
--- a/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md
+++ b/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md
@@ -9,9 +9,5 @@ Client used to query the elasticsearch cluster.
Signature:
```typescript
-export declare type ElasticsearchClient = Omit & {
- transport: {
- request(params: TransportRequestParams, options?: TransportRequestOptions): Promise>;
- };
-};
+export declare type ElasticsearchClient = Omit;
```
diff --git a/examples/preboot_example/server/plugin.ts b/examples/preboot_example/server/plugin.ts
index a3c1e9d199143..288b5245c82b1 100644
--- a/examples/preboot_example/server/plugin.ts
+++ b/examples/preboot_example/server/plugin.ts
@@ -114,7 +114,7 @@ export class PrebootExamplePlugin implements PrebootPlugin {
try {
return response.ok({
- body: (await scopedClient.asCurrentUser.security.authenticate()).body,
+ body: await scopedClient.asCurrentUser.security.authenticate(),
});
} catch (err) {
return response.customError({ statusCode: 500, body: getDetailedErrorMessage(err) });
diff --git a/packages/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts b/packages/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts
index 95fa040142c15..90ca50aa17c22 100644
--- a/packages/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts
@@ -9,7 +9,7 @@
// Copied from src/core/server/elasticsearch/client/types.ts
// as these types aren't part of any package yet. Once they are, remove this completely
-import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
/**
* Client used to query the elasticsearch cluster.
@@ -17,6 +17,6 @@ import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
* @public
*/
export type ElasticsearchClient = Omit<
- KibanaClient,
- 'connectionPool' | 'transport' | 'serializer' | 'extend' | 'child' | 'close' | 'diagnostic'
+ Client,
+ 'connectionPool' | 'serializer' | 'extend' | 'child' | 'close' | 'diagnostic'
>;
diff --git a/packages/kbn-securitysolution-es-utils/src/get_bootstrap_index_exists/index.ts b/packages/kbn-securitysolution-es-utils/src/get_bootstrap_index_exists/index.ts
index 959e38b3f7ee4..a743a9b66af54 100644
--- a/packages/kbn-securitysolution-es-utils/src/get_bootstrap_index_exists/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/get_bootstrap_index_exists/index.ts
@@ -22,7 +22,7 @@ export const getBootstrapIndexExists = async (
index: string
): Promise => {
try {
- const { body } = await esClient.indices.getAlias({
+ const body = await esClient.indices.getAlias({
index: `${index}-*`,
name: index,
});
diff --git a/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts b/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts
index 9a0d0fed1b63e..0df165a6b8b73 100644
--- a/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts
@@ -8,16 +8,6 @@
import type { ElasticsearchClient } from '../elasticsearch_client';
-interface AliasesResponse {
- [indexName: string]: {
- aliases: {
- [aliasName: string]: {
- is_write_index: boolean;
- };
- };
- };
-}
-
interface IndexAlias {
alias: string;
index: string;
@@ -39,7 +29,7 @@ export const getIndexAliases = async ({
esClient: ElasticsearchClient;
alias: string;
}): Promise => {
- const response = await esClient.indices.getAlias(
+ const response = await esClient.indices.getAlias(
{
name: alias,
},
diff --git a/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts b/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts
index 59cae505bfded..6d7b35a00ae75 100644
--- a/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts
@@ -23,7 +23,7 @@ export const getIndexCount = async ({
esClient: ElasticsearchClient;
index: string;
}): Promise => {
- const response = await esClient.count<{ count: number }>(
+ const response = await esClient.count(
{
index,
},
diff --git a/packages/kbn-test/src/es/client_to_kibana_client.ts b/packages/kbn-test/src/es/client_to_kibana_client.ts
deleted file mode 100644
index 778ee0a7705b3..0000000000000
--- a/packages/kbn-test/src/es/client_to_kibana_client.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
- * or more contributor license agreements. Licensed under the Elastic License
- * 2.0 and the Server Side Public License, v 1; you may not use this file except
- * in compliance with, at your election, the Elastic License 2.0 or the Server
- * Side Public License, v 1.
- */
-import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
-import type {
- Client,
- TransportRequestParams,
- TransportRequestOptions,
- TransportResult,
-} from '@elastic/elasticsearch';
-import { Transport } from '@elastic/elasticsearch';
-
-// remove once https://github.com/elastic/kibana/issues/116095 is addressed
-class KibanaTransport extends Transport {
- request(params: TransportRequestParams, options?: TransportRequestOptions) {
- const opts: TransportRequestOptions = options || {};
- // Enforce the client to return TransportResult.
- // It's required for bwc with responses in 7.x version.
- if (opts?.meta === undefined) {
- opts.meta = true;
- }
- return super.request(params, opts) as Promise>;
- }
-}
-
-export function convertToKibanaClient(esClient: Client): KibanaClient {
- // @ts-expect-error @elastic/elasticsearch fix discrepancy between clients
- return esClient.child({
- Transport: KibanaTransport,
- });
-}
diff --git a/packages/kbn-test/src/es/index.ts b/packages/kbn-test/src/es/index.ts
index c823adaab101f..641253acc3647 100644
--- a/packages/kbn-test/src/es/index.ts
+++ b/packages/kbn-test/src/es/index.ts
@@ -9,6 +9,5 @@
export { createTestEsCluster } from './test_es_cluster';
export type { CreateTestEsClusterOptions, EsTestCluster, ICluster } from './test_es_cluster';
export { esTestConfig } from './es_test_config';
-export { convertToKibanaClient } from './client_to_kibana_client';
export { createEsClientForTesting, createEsClientForFtrConfig } from './es_client_for_testing';
export type { EsClientForTestingOptions } from './es_client_for_testing';
diff --git a/packages/kbn-test/src/es/test_es_cluster.ts b/packages/kbn-test/src/es/test_es_cluster.ts
index 575fc965962eb..388d578c9af57 100644
--- a/packages/kbn-test/src/es/test_es_cluster.ts
+++ b/packages/kbn-test/src/es/test_es_cluster.ts
@@ -12,11 +12,9 @@ import del from 'del';
// @ts-expect-error in js
import { Cluster } from '@kbn/es';
import { Client, HttpConnection } from '@elastic/elasticsearch';
-import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import type { ToolingLog } from '@kbn/dev-utils';
import { CI_PARALLEL_PROCESS_PREFIX } from '../ci_parallel_process_prefix';
import { esTestConfig } from './es_test_config';
-import { convertToKibanaClient } from './client_to_kibana_client';
import { KIBANA_ROOT } from '../';
@@ -53,7 +51,6 @@ export interface ICluster {
stop: () => Promise;
cleanup: () => Promise;
getClient: () => Client;
- getKibanaEsClient: () => KibanaClient;
getHostUrls: () => string[];
}
@@ -289,13 +286,6 @@ export function createTestEsCluster<
});
}
- /**
- * Returns an ES Client to the configured cluster
- */
- getKibanaEsClient(): KibanaClient {
- return convertToKibanaClient(this.getClient());
- }
-
getUrl() {
if (this.nodes.length > 1) {
throw new Error(
diff --git a/packages/kbn-test/src/index.ts b/packages/kbn-test/src/index.ts
index 5efd1c1f26852..26d40f70edb78 100644
--- a/packages/kbn-test/src/index.ts
+++ b/packages/kbn-test/src/index.ts
@@ -34,7 +34,6 @@ export type {
export {
esTestConfig,
createTestEsCluster,
- convertToKibanaClient,
createEsClientForTesting,
createEsClientForFtrConfig,
} from './es';
diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md
index d8cf4706ceb16..6d2ee9a5dd4e1 100644
--- a/src/core/public/public.api.md
+++ b/src/core/public/public.api.md
@@ -9,6 +9,7 @@
import { Action } from 'history';
import Boom from '@hapi/boom';
import { ByteSizeValue } from '@kbn/config-schema';
+import type { Client } from '@elastic/elasticsearch';
import { ConfigPath } from '@kbn/config';
import { DetailedPeerCertificate } from 'tls';
import type { DocLinks } from '@kbn/doc-links';
@@ -24,7 +25,6 @@ import { History as History_2 } from 'history';
import { Href } from 'history';
import { IconType } from '@elastic/eui';
import { IncomingHttpHeaders } from 'http';
-import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import { Location as Location_2 } from 'history';
import { LocationDescriptorObject } from 'history';
import { Logger } from '@kbn/logging';
@@ -44,9 +44,6 @@ import * as Rx from 'rxjs';
import { SchemaTypeError } from '@kbn/config-schema';
import type { ThemeVersion } from '@kbn/ui-shared-deps-npm';
import { TransitionPromptHook } from 'history';
-import type { TransportRequestOptions } from '@elastic/elasticsearch';
-import type { TransportRequestParams } from '@elastic/elasticsearch';
-import type { TransportResult } from '@elastic/elasticsearch';
import { Type } from '@kbn/config-schema';
import { TypeOf } from '@kbn/config-schema';
import { UiCounterMetricType } from '@kbn/analytics';
diff --git a/src/core/server/core_usage_data/core_usage_data_service.test.ts b/src/core/server/core_usage_data/core_usage_data_service.test.ts
index e6e890b1a7dab..b2315a7cde281 100644
--- a/src/core/server/core_usage_data/core_usage_data_service.test.ts
+++ b/src/core/server/core_usage_data/core_usage_data_service.test.ts
@@ -207,47 +207,37 @@ describe('CoreUsageDataService', () => {
});
service.setup({ http, metrics, savedObjectsStartPromise, changedDeprecatedConfigPath$ });
const elasticsearch = elasticsearchServiceMock.createStart();
- elasticsearch.client.asInternalUser.cat.indices.mockResolvedValueOnce({
- body: [
- {
- name: '.kibana_task_manager_1',
- 'docs.count': '10',
- 'docs.deleted': '10',
- 'store.size': '1000',
- 'pri.store.size': '2000',
- },
- ],
- } as any);
- elasticsearch.client.asInternalUser.count.mockResolvedValueOnce({
- body: {
- count: '15',
+ elasticsearch.client.asInternalUser.cat.indices.mockResponseOnce([
+ {
+ name: '.kibana_task_manager_1',
+ 'docs.count': '10',
+ 'docs.deleted': '10',
+ 'store.size': '1000',
+ 'pri.store.size': '2000',
},
+ ] as any);
+ elasticsearch.client.asInternalUser.count.mockResponseOnce({
+ count: '15',
} as any);
- elasticsearch.client.asInternalUser.cat.indices.mockResolvedValueOnce({
- body: [
- {
- name: '.kibana_1',
- 'docs.count': '20',
- 'docs.deleted': '20',
- 'store.size': '2000',
- 'pri.store.size': '4000',
- },
- ],
- } as any);
- elasticsearch.client.asInternalUser.count.mockResolvedValueOnce({
- body: {
- count: '10',
+ elasticsearch.client.asInternalUser.cat.indices.mockResponseOnce([
+ {
+ name: '.kibana_1',
+ 'docs.count': '20',
+ 'docs.deleted': '20',
+ 'store.size': '2000',
+ 'pri.store.size': '4000',
},
+ ] as any);
+ elasticsearch.client.asInternalUser.count.mockResponseOnce({
+ count: '10',
} as any);
- elasticsearch.client.asInternalUser.search.mockResolvedValueOnce({
- body: {
- hits: { total: { value: 6 } },
- aggregations: {
- aliases: {
- buckets: {
- active: { doc_count: 1 },
- disabled: { doc_count: 2 },
- },
+ elasticsearch.client.asInternalUser.search.mockResponseOnce({
+ hits: { total: { value: 6 } },
+ aggregations: {
+ aliases: {
+ buckets: {
+ active: { doc_count: 1 },
+ disabled: { doc_count: 2 },
},
},
},
diff --git a/src/core/server/core_usage_data/core_usage_data_service.ts b/src/core/server/core_usage_data/core_usage_data_service.ts
index 824bfdffdceec..bdd46932fd9a9 100644
--- a/src/core/server/core_usage_data/core_usage_data_service.ts
+++ b/src/core/server/core_usage_data/core_usage_data_service.ts
@@ -136,12 +136,12 @@ export class CoreUsageDataService
// to map back from the index to the alias. So we have to make an API
// call for every alias. The document count is the lucene document count.
const catIndicesResults = await elasticsearch.client.asInternalUser.cat
- .indices({
+ .indices({
index,
format: 'JSON',
bytes: 'b',
})
- .then(({ body }) => {
+ .then((body) => {
const stats = body[0];
return {
@@ -160,7 +160,7 @@ export class CoreUsageDataService
.count({
index,
})
- .then(({ body }) => {
+ .then((body) => {
return {
savedObjectsDocsCount: body.count ? body.count : 0,
};
@@ -182,7 +182,7 @@ export class CoreUsageDataService
private async getSavedObjectAliasUsageData(elasticsearch: ElasticsearchServiceStart) {
// Note: this agg can be changed to use `savedObjectsRepository.find` in the future after `filters` is supported.
// See src/core/server/saved_objects/service/lib/aggregations/aggs_types/bucket_aggs.ts for supported aggregations.
- const { body: resp } = await elasticsearch.client.asInternalUser.search<
+ const resp = await elasticsearch.client.asInternalUser.search<
unknown,
{ aliases: UsageDataAggs }
>({
diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts
index 6bf74294ab6c1..038fe109b3988 100644
--- a/src/core/server/elasticsearch/client/cluster_client.ts
+++ b/src/core/server/elasticsearch/client/cluster_client.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import { Logger } from '../../logging';
import { IAuthHeadersStorage, Headers, isKibanaRequest, isRealRequest } from '../../http';
import { ensureRawRequest, filterHeaders } from '../../http/router';
@@ -60,12 +60,12 @@ export interface ICustomClusterClient extends IClusterClient {
export class ClusterClient implements ICustomClusterClient {
private readonly config: ElasticsearchClientConfig;
private readonly authHeaders?: IAuthHeadersStorage;
- private readonly rootScopedClient: KibanaClient;
+ private readonly rootScopedClient: Client;
private readonly getUnauthorizedErrorHandler: () => UnauthorizedErrorHandler | undefined;
private readonly getExecutionContext: () => string | undefined;
private isClosed = false;
- public readonly asInternalUser: KibanaClient;
+ public readonly asInternalUser: Client;
constructor({
config,
diff --git a/src/core/server/elasticsearch/client/configure_client.ts b/src/core/server/elasticsearch/client/configure_client.ts
index 58d1e228b98a0..e1e4a1846852b 100644
--- a/src/core/server/elasticsearch/client/configure_client.ts
+++ b/src/core/server/elasticsearch/client/configure_client.ts
@@ -7,7 +7,6 @@
*/
import { Client, HttpConnection } from '@elastic/elasticsearch';
-import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import { Logger } from '../../logging';
import { parseClientOptions, ElasticsearchClientConfig } from './client_config';
import { instrumentEsQueryAndDeprecationLogger } from './log_query_and_deprecation';
@@ -28,7 +27,7 @@ export const configureClient = (
scoped?: boolean;
getExecutionContext?: () => string | undefined;
}
-): KibanaClient => {
+): Client => {
const clientOptions = parseClientOptions(config, scoped);
const KibanaTransport = createTransport({ getExecutionContext });
@@ -40,5 +39,5 @@ export const configureClient = (
instrumentEsQueryAndDeprecationLogger({ logger, client, type });
- return client as KibanaClient;
+ return client;
};
diff --git a/src/core/server/elasticsearch/client/create_transport.test.ts b/src/core/server/elasticsearch/client/create_transport.test.ts
index df2717e7ce9e6..ce54d8356f38b 100644
--- a/src/core/server/elasticsearch/client/create_transport.test.ts
+++ b/src/core/server/elasticsearch/client/create_transport.test.ts
@@ -116,7 +116,7 @@ describe('createTransport', () => {
});
describe('`meta` option', () => {
- it('adds `meta: true` to the options when not provided', async () => {
+ it('does not adds `meta: true` to the options when not provided', async () => {
const transportClass = createTransportClass();
const transport = new transportClass(baseConstructorParams);
const requestOptions = { method: 'GET', path: '/' };
@@ -126,7 +126,7 @@ describe('createTransport', () => {
expect(transportRequestMock).toHaveBeenCalledTimes(1);
expect(transportRequestMock).toHaveBeenCalledWith(
expect.any(Object),
- expect.objectContaining({
+ expect.not.objectContaining({
meta: true,
})
);
diff --git a/src/core/server/elasticsearch/client/create_transport.ts b/src/core/server/elasticsearch/client/create_transport.ts
index d72fae58c88cf..7ebe61afabdd0 100644
--- a/src/core/server/elasticsearch/client/create_transport.ts
+++ b/src/core/server/elasticsearch/client/create_transport.ts
@@ -46,11 +46,6 @@ export const createTransport = ({
// rewrites headers['x-opaque-id'] if it presents
opts.opaqueId = opaqueId;
}
- // Enforce the client to return TransportResult.
- // It's required for bwc with responses in 7.x version.
- if (opts.meta === undefined) {
- opts.meta = true;
- }
// add stored headers to the options
opts.headers = {
diff --git a/src/core/server/elasticsearch/client/mocks.test.ts b/src/core/server/elasticsearch/client/mocks.test.ts
index 30b50e19f6c7e..6c7f34112117c 100644
--- a/src/core/server/elasticsearch/client/mocks.test.ts
+++ b/src/core/server/elasticsearch/client/mocks.test.ts
@@ -47,9 +47,156 @@ describe('Mocked client', () => {
it('`child` should be mocked and return a mocked Client', () => {
expectMocked(client.child);
- const child = client.child();
+ const child = client.child({});
expect(child).not.toBe(client);
expectMocked(child.search);
});
+
+ describe('mockResponse', () => {
+ beforeEach(() => {
+ client.ping.mockReset();
+ client.ping.mockResponse(true, { statusCode: 217, headers: { foo: 'bar' } });
+ });
+
+ it('returns the body when `meta` is false', async () => {
+ const response = await client.ping({}, { meta: false });
+ expect(response).toBe(true);
+ });
+ it('returns the response when `meta` is true', async () => {
+ const response = await client.ping({}, { meta: true });
+ expect(response).toEqual({
+ body: true,
+ statusCode: 217,
+ headers: { foo: 'bar' },
+ warnings: [],
+ meta: {},
+ });
+ });
+ it('returns the body when `meta` is not provided', async () => {
+ const response = await client.ping({}, {});
+ expect(response).toBe(true);
+ });
+ it('mocks the response multiple times', async () => {
+ expect(await client.ping({}, {})).toBe(true);
+ expect(await client.ping({}, {})).toBe(true);
+ expect(await client.ping({}, {})).toBe(true);
+ });
+ });
+ describe('mockResponseOnce', () => {
+ beforeEach(() => {
+ client.ping.mockReset();
+ client.ping.mockResponseOnce(true, { statusCode: 217, headers: { foo: 'bar' } });
+ });
+
+ it('returns the body when `meta` is false', async () => {
+ const response = await client.ping({}, { meta: false });
+ expect(response).toBe(true);
+ });
+ it('returns the response when `meta` is true', async () => {
+ const response = await client.ping({}, { meta: true });
+ expect(response).toEqual({
+ body: true,
+ statusCode: 217,
+ headers: { foo: 'bar' },
+ warnings: [],
+ meta: {},
+ });
+ });
+ it('returns the body when `meta` is not provided', async () => {
+ const response = await client.ping({}, {});
+ expect(response).toBe(true);
+ });
+ it('mocks the response only once', async () => {
+ expect(await client.ping({}, {})).toBe(true);
+ expect(await client.ping({}, {})).toBe(undefined);
+ });
+ it('can be chained', async () => {
+ client.ping.mockReset();
+ client.ping.mockResponseOnce(true);
+ client.ping.mockResponseOnce(false);
+ client.ping.mockResponseOnce(true);
+
+ expect(await client.ping({}, {})).toBe(true);
+ expect(await client.ping({}, {})).toBe(false);
+ expect(await client.ping({}, {})).toBe(true);
+ });
+ });
+ describe('mockResponseImplementation', () => {
+ beforeEach(() => {
+ client.ping.mockReset();
+ client.ping.mockResponseImplementation(() => ({
+ body: true,
+ statusCode: 217,
+ headers: { foo: 'bar' },
+ }));
+ });
+
+ it('returns the body when `meta` is false', async () => {
+ const response = await client.ping({}, { meta: false });
+ expect(response).toBe(true);
+ });
+ it('returns the response when `meta` is true', async () => {
+ const response = await client.ping({}, { meta: true });
+ expect(response).toEqual({
+ body: true,
+ statusCode: 217,
+ headers: { foo: 'bar' },
+ warnings: [],
+ meta: {},
+ });
+ });
+ it('returns the body when `meta` is not provided', async () => {
+ const response = await client.ping({}, {});
+ expect(response).toBe(true);
+ });
+ it('mocks the response multiple times', async () => {
+ expect(await client.ping({}, {})).toBe(true);
+ expect(await client.ping({}, {})).toBe(true);
+ expect(await client.ping({}, {})).toBe(true);
+ });
+ });
+ describe('mockResponseImplementationOnce', () => {
+ beforeEach(() => {
+ client.ping.mockReset();
+ client.ping.mockResponseImplementationOnce(() => ({
+ body: true,
+ statusCode: 217,
+ headers: { foo: 'bar' },
+ }));
+ });
+
+ it('returns the body when `meta` is false', async () => {
+ const response = await client.ping({}, { meta: false });
+ expect(response).toBe(true);
+ });
+ it('returns the response when `meta` is true', async () => {
+ const response = await client.ping({}, { meta: true });
+ expect(response).toEqual({
+ body: true,
+ statusCode: 217,
+ headers: { foo: 'bar' },
+ warnings: [],
+ meta: {},
+ });
+ });
+ it('returns the body when `meta` is not provided', async () => {
+ const response = await client.ping({}, {});
+ expect(response).toBe(true);
+ });
+ it('mocks the response only once', async () => {
+ expect(await client.ping({}, {})).toBe(true);
+ expect(await client.ping({}, {})).toBe(undefined);
+ });
+ it('can be chained', async () => {
+ client.ping.mockReset();
+ client.ping.mockResponseImplementationOnce(() => ({ body: true }));
+ client.ping.mockResponseImplementationOnce(() => ({ body: false }));
+ client.ping.mockResponseImplementationOnce(() => ({ body: true }));
+
+ expect(await client.ping({}, {})).toBe(true);
+ expect(await client.ping({}, {})).toBe(false);
+ expect(await client.ping({}, {})).toBe(true);
+ });
+ });
});
diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts
index 4cb31438791e0..2c34629f2fd57 100644
--- a/src/core/server/elasticsearch/client/mocks.ts
+++ b/src/core/server/elasticsearch/client/mocks.ts
@@ -6,9 +6,8 @@
* Side Public License, v 1.
*/
-import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
-import type { TransportResult } from '@elastic/elasticsearch';
-import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
+import type { Client } from '@elastic/elasticsearch';
+import type { TransportResult, TransportRequestOptions } from '@elastic/elasticsearch';
import type { PublicKeys } from '@kbn/utility-types';
import { ElasticsearchClient } from './types';
import { ICustomClusterClient } from './cluster_client';
@@ -21,11 +20,110 @@ const omittedProps = [
'transport',
'serializer',
'helpers',
-] as Array>;
+] as Array>;
+
+export type DeeplyMockedApi = {
+ [P in keyof T]: T[P] extends (...args: any[]) => any
+ ? ClientApiMockInstance, Parameters>
+ : DeeplyMockedApi;
+} & T;
+
+export interface ClientApiMockInstance extends jest.MockInstance {
+ /**
+ * Helper API around `mockReturnValue` returning either the body or the whole TransportResult
+ * depending on the `meta` parameter used during the call
+ */
+ mockResponse(value: Awaited, opts?: Partial, 'body'>>): this;
+
+ /**
+ * Helper API around `mockReturnValueOnce` returning either the body or the whole TransportResult
+ * depending on the `meta` parameter used during the call
+ */
+ mockResponseOnce(value: Awaited, opts?: Partial, 'body'>>): this;
+
+ /**
+ * Helper API around `mockImplementation` returning either the body or the whole TransportResult
+ * depending on the `meta` parameter used during the call
+ */
+ mockResponseImplementation(handler: (...args: Y) => Partial>>): this;
+
+ /**
+ * Helper API around `mockImplementationOnce` returning either the body or the whole TransportResult
+ * depending on the `meta` parameter used during the call
+ */
+ mockResponseImplementationOnce(
+ handler: (...args: Y) => Partial>>
+ ): this;
+}
+
+const createMockedApi = <
+ T = unknown,
+ Y extends [any, TransportRequestOptions] = [any, TransportRequestOptions]
+>(): ClientApiMockInstance => {
+ const mock: ClientApiMockInstance = jest.fn() as any;
+
+ mock.mockResponse = (value: T, opts?: Partial, 'body'>>) => {
+ mock.mockImplementation((args: unknown, options?: TransportRequestOptions) => {
+ const meta = options?.meta ?? false;
+ if (meta) {
+ return Promise.resolve(createApiResponse({ ...opts, body: value })) as any;
+ } else {
+ return Promise.resolve(value) as Promise;
+ }
+ });
+ return mock;
+ };
+
+ mock.mockResponseOnce = (value: T, opts?: Partial, 'body'>>) => {
+ mock.mockImplementationOnce((args: unknown, options?: TransportRequestOptions) => {
+ const meta = options?.meta ?? false;
+ if (meta) {
+ return Promise.resolve(createApiResponse({ ...opts, body: value })) as any;
+ } else {
+ return Promise.resolve(value) as Promise;
+ }
+ });
+ return mock;
+ };
+
+ mock.mockResponseImplementation = (
+ handler: (...args: Y) => Partial>>
+ ) => {
+ mock.mockImplementation((args: unknown, options?: TransportRequestOptions) => {
+ const meta = options?.meta ?? false;
+ // @ts-expect-error couldn't do better while keeping compatibility this jest.MockInstance
+ const response = handler(args, options);
+ if (meta) {
+ return Promise.resolve(createApiResponse(response)) as any;
+ } else {
+ return Promise.resolve(response.body ?? {}) as Promise;
+ }
+ });
+ return mock;
+ };
+
+ mock.mockResponseImplementationOnce = (
+ handler: (...args: Y) => Partial>>
+ ) => {
+ mock.mockImplementationOnce((args: unknown, options?: TransportRequestOptions) => {
+ const meta = options?.meta ?? false;
+ // @ts-expect-error couldn't do better while keeping compatibility this jest.MockInstance
+ const response = handler(args, options);
+ if (meta) {
+ return Promise.resolve(createApiResponse(response)) as any;
+ } else {
+ return Promise.resolve(response.body ?? {}) as Promise;
+ }
+ });
+ return mock;
+ };
+
+ return mock;
+};
// use jest.requireActual() to prevent weird errors when people mock @elastic/elasticsearch
const { Client: UnmockedClient } = jest.requireActual('@elastic/elasticsearch');
-const createInternalClientMock = (res?: Promise): DeeplyMockedKeys => {
+const createInternalClientMock = (res?: Promise): DeeplyMockedApi => {
// we mimic 'reflection' on a concrete instance of the client to generate the mocked functions.
const client = new UnmockedClient({
node: 'http://127.0.0.1',
@@ -50,14 +148,16 @@ const createInternalClientMock = (res?: Promise): DeeplyMockedKeys !omitted.includes(key))
.forEach(([key, descriptor]) => {
if (typeof descriptor.value === 'function') {
- obj[key] = jest.fn(() => res ?? createSuccessTransportRequestPromise({}));
+ const mock = createMockedApi();
+ mock.mockImplementation(() => res ?? createSuccessTransportRequestPromise({}));
+ obj[key] = mock;
} else if (typeof obj[key] === 'object' && obj[key] != null) {
mockify(obj[key], omitted);
}
});
};
- mockify(client, omittedProps);
+ mockify(client, omittedProps as string[]);
client.close = jest.fn().mockReturnValue(Promise.resolve());
client.child = jest.fn().mockImplementation(() => createInternalClientMock());
@@ -81,10 +181,10 @@ const createInternalClientMock = (res?: Promise): DeeplyMockedKeys;
+ return client as DeeplyMockedApi;
};
-export type ElasticsearchClientMock = DeeplyMockedKeys;
+export type ElasticsearchClientMock = DeeplyMockedApi;
const createClientMock = (res?: Promise): ElasticsearchClientMock =>
createInternalClientMock(res) as unknown as ElasticsearchClientMock;
@@ -138,13 +238,12 @@ const createSuccessTransportRequestPromise = (
body: T,
{ statusCode = 200 }: { statusCode?: number } = {},
headers: Record = { [PRODUCT_RESPONSE_HEADER]: 'Elasticsearch' }
-): Promise> => {
+): Promise & T> => {
const response = createApiResponse({ body, statusCode, headers });
-
- return Promise.resolve(response) as Promise>;
+ return Promise.resolve(response) as Promise & T>;
};
-const createErrorTransportRequestPromise = (err: any): Promise> => {
+const createErrorTransportRequestPromise = (err: any): Promise => {
return Promise.reject(err);
};
diff --git a/src/core/server/elasticsearch/client/retry_call_cluster.test.ts b/src/core/server/elasticsearch/client/retry_call_cluster.test.ts
index 636841316941b..c2a9dd6ab91c8 100644
--- a/src/core/server/elasticsearch/client/retry_call_cluster.test.ts
+++ b/src/core/server/elasticsearch/client/retry_call_cluster.test.ts
@@ -23,37 +23,27 @@ describe('retryCallCluster', () => {
});
it('returns response from ES API call in case of success', async () => {
- const successReturn = elasticsearchClientMock.createSuccessTransportRequestPromise({
- ...dummyBody,
- });
-
- client.asyncSearch.get.mockReturnValue(successReturn);
+ client.asyncSearch.get.mockResponseOnce(dummyBody);
const result = await retryCallCluster(() => client.asyncSearch.get({} as any));
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('retries ES API calls that rejects with `NoLivingConnectionsError`', async () => {
- const successReturn = elasticsearchClientMock.createSuccessTransportRequestPromise({
- ...dummyBody,
- });
-
client.asyncSearch.get
.mockImplementationOnce(() =>
createErrorReturn(new errors.NoLivingConnectionsError('no living connections', {} as any))
)
- .mockImplementationOnce(() => successReturn);
+ .mockResponseOnce(dummyBody);
const result = await retryCallCluster(() => client.asyncSearch.get({} as any));
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('rejects when ES API calls reject with other errors', async () => {
client.ping
.mockImplementationOnce(() => createErrorReturn(new Error('unknown error')))
- .mockImplementationOnce(() =>
- elasticsearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody })
- );
+ .mockResponseOnce(dummyBody);
await expect(retryCallCluster(() => client.ping())).rejects.toMatchInlineSnapshot(
`[Error: unknown error]`
@@ -69,9 +59,7 @@ describe('retryCallCluster', () => {
createErrorReturn(new errors.NoLivingConnectionsError('no living connections', {} as any))
)
.mockImplementationOnce(() => createErrorReturn(new Error('unknown error')))
- .mockImplementationOnce(() =>
- elasticsearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody })
- );
+ .mockResponseOnce(dummyBody);
await expect(retryCallCluster(() => client.ping())).rejects.toMatchInlineSnapshot(
`[Error: unknown error]`
@@ -92,9 +80,7 @@ describe('migrationRetryCallCluster', () => {
client.ping
.mockImplementationOnce(() => createErrorReturn(error))
.mockImplementationOnce(() => createErrorReturn(error))
- .mockImplementationOnce(() =>
- elasticsearchClientMock.createSuccessTransportRequestPromise({ ...dummyBody })
- );
+ .mockResponseOnce(dummyBody);
};
it('retries ES API calls that rejects with `NoLivingConnectionsError`', async () => {
@@ -103,21 +89,21 @@ describe('migrationRetryCallCluster', () => {
);
const result = await migrationRetryCallCluster(() => client.ping(), logger, 1);
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('retries ES API calls that rejects with `ConnectionError`', async () => {
mockClientPingWithErrorBeforeSuccess(new errors.ConnectionError('connection error', {} as any));
const result = await migrationRetryCallCluster(() => client.ping(), logger, 1);
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('retries ES API calls that rejects with `TimeoutError`', async () => {
mockClientPingWithErrorBeforeSuccess(new errors.TimeoutError('timeout error', {} as any));
const result = await migrationRetryCallCluster(() => client.ping(), logger, 1);
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('retries ES API calls that rejects with 503 `ResponseError`', async () => {
@@ -128,7 +114,7 @@ describe('migrationRetryCallCluster', () => {
);
const result = await migrationRetryCallCluster(() => client.ping(), logger, 1);
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('retries ES API calls that rejects 401 `ResponseError`', async () => {
@@ -139,7 +125,7 @@ describe('migrationRetryCallCluster', () => {
);
const result = await migrationRetryCallCluster(() => client.ping(), logger, 1);
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('retries ES API calls that rejects with 403 `ResponseError`', async () => {
@@ -150,7 +136,7 @@ describe('migrationRetryCallCluster', () => {
);
const result = await migrationRetryCallCluster(() => client.ping(), logger, 1);
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('retries ES API calls that rejects with 408 `ResponseError`', async () => {
@@ -161,7 +147,7 @@ describe('migrationRetryCallCluster', () => {
);
const result = await migrationRetryCallCluster(() => client.ping(), logger, 1);
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('retries ES API calls that rejects with 410 `ResponseError`', async () => {
@@ -172,7 +158,7 @@ describe('migrationRetryCallCluster', () => {
);
const result = await migrationRetryCallCluster(() => client.ping(), logger, 1);
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('retries ES API calls that rejects with `snapshot_in_progress_exception` `ResponseError`', async () => {
@@ -188,7 +174,7 @@ describe('migrationRetryCallCluster', () => {
);
const result = await migrationRetryCallCluster(() => client.ping(), logger, 1);
- expect(result.body).toEqual(dummyBody);
+ expect(result).toEqual(dummyBody);
});
it('logs only once for each unique error message', async () => {
diff --git a/src/core/server/elasticsearch/client/types.ts b/src/core/server/elasticsearch/client/types.ts
index e168a4a4a9c21..68fbc87193074 100644
--- a/src/core/server/elasticsearch/client/types.ts
+++ b/src/core/server/elasticsearch/client/types.ts
@@ -6,12 +6,7 @@
* Side Public License, v 1.
*/
-import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
-import type {
- TransportResult,
- TransportRequestOptions,
- TransportRequestParams,
-} from '@elastic/elasticsearch';
+import type { Client } from '@elastic/elasticsearch';
/**
* Client used to query the elasticsearch cluster.
@@ -19,16 +14,9 @@ import type {
* @public
*/
export type ElasticsearchClient = Omit<
- KibanaClient,
- 'connectionPool' | 'transport' | 'serializer' | 'extend' | 'child' | 'close' | 'diagnostic'
-> & {
- transport: {
- request(
- params: TransportRequestParams,
- options?: TransportRequestOptions
- ): Promise>;
- };
-};
+ Client,
+ 'connectionPool' | 'serializer' | 'extend' | 'child' | 'close' | 'diagnostic'
+>;
/**
* All response typings are maintained until elasticsearch-js provides them out of the box
diff --git a/src/core/server/elasticsearch/integration_tests/client.test.ts b/src/core/server/elasticsearch/integration_tests/client.test.ts
index 05100564dac03..96a9d70d1b651 100644
--- a/src/core/server/elasticsearch/integration_tests/client.test.ts
+++ b/src/core/server/elasticsearch/integration_tests/client.test.ts
@@ -39,16 +39,19 @@ describe('elasticsearch clients', () => {
it('does not return deprecation warning when x-elastic-product-origin header is set', async () => {
// Header should be automatically set by Core
const resp1 =
- await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings({
- index: '.kibana',
- });
+ await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings(
+ {
+ index: '.kibana',
+ },
+ { meta: true }
+ );
expect(resp1.headers).not.toHaveProperty('warning');
// Also test setting it explicitly
const resp2 =
await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings(
{ index: '.kibana' },
- { headers: { 'x-elastic-product-origin': 'kibana' } }
+ { headers: { 'x-elastic-product-origin': 'kibana' }, meta: true }
);
expect(resp2.headers).not.toHaveProperty('warning');
});
diff --git a/src/core/server/elasticsearch/is_scripting_enabled.test.ts b/src/core/server/elasticsearch/is_scripting_enabled.test.ts
index dd84c29818556..797ff8972b7be 100644
--- a/src/core/server/elasticsearch/is_scripting_enabled.test.ts
+++ b/src/core/server/elasticsearch/is_scripting_enabled.test.ts
@@ -18,9 +18,7 @@ describe('isInlineScriptingEnabled', () => {
});
const mockSettingsValue = (settings: estypes.ClusterGetSettingsResponse) => {
- client.cluster.getSettings.mockReturnValue(
- elasticsearchServiceMock.createSuccessTransportRequestPromise(settings)
- );
+ client.cluster.getSettings.mockResolvedValue(settings);
};
it('returns `true` if all settings are empty', async () => {
diff --git a/src/core/server/elasticsearch/is_scripting_enabled.ts b/src/core/server/elasticsearch/is_scripting_enabled.ts
index 31276a8c72aef..13685362c11ca 100644
--- a/src/core/server/elasticsearch/is_scripting_enabled.ts
+++ b/src/core/server/elasticsearch/is_scripting_enabled.ts
@@ -15,7 +15,7 @@ export const isInlineScriptingEnabled = async ({
}: {
client: ElasticsearchClient;
}): Promise => {
- const { body: settings } = await client.cluster.getSettings({
+ const settings = await client.cluster.getSettings({
include_defaults: true,
flat_settings: true,
});
diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts
index c9bb82d5da65c..9dfb2463f0893 100644
--- a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts
+++ b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts
@@ -18,10 +18,6 @@ const mockLogger = mockLoggerFactory.get('mock logger');
const KIBANA_VERSION = '5.1.0';
-const createEsSuccess = elasticsearchClientMock.createSuccessTransportRequestPromise;
-const createEsErrorReturn = (err: any) =>
- elasticsearchClientMock.createErrorTransportRequestPromise(err);
-
function createNodes(...versions: string[]): NodesInfo {
const nodes = {} as any;
versions
@@ -140,10 +136,10 @@ describe('pollEsNodesVersion', () => {
const nodeInfosSuccessOnce = (infos: NodesInfo) => {
// @ts-expect-error not full interface
- internalClient.nodes.info.mockImplementationOnce(() => createEsSuccess(infos));
+ internalClient.nodes.info.mockResponseOnce(infos);
};
const nodeInfosErrorOnce = (error: any) => {
- internalClient.nodes.info.mockImplementationOnce(() => createEsErrorReturn(new Error(error)));
+ internalClient.nodes.info.mockImplementationOnce(() => Promise.reject(new Error(error)));
};
it('returns isCompatible=false and keeps polling when a poll request throws', (done) => {
@@ -317,13 +313,9 @@ describe('pollEsNodesVersion', () => {
expect.assertions(1);
// @ts-expect-error we need to return an incompatible type to use the testScheduler here
- internalClient.nodes.info.mockReturnValueOnce([
- { body: createNodes('5.1.0', '5.2.0', '5.0.0') },
- ]);
+ internalClient.nodes.info.mockReturnValueOnce([createNodes('5.1.0', '5.2.0', '5.0.0')]);
// @ts-expect-error we need to return an incompatible type to use the testScheduler here
- internalClient.nodes.info.mockReturnValueOnce([
- { body: createNodes('5.1.1', '5.2.0', '5.0.0') },
- ]);
+ internalClient.nodes.info.mockReturnValueOnce([createNodes('5.1.1', '5.2.0', '5.0.0')]);
getTestScheduler().run(({ expectObservable }) => {
const expected = 'a 99ms (b|)';
@@ -359,11 +351,11 @@ describe('pollEsNodesVersion', () => {
internalClient.nodes.info.mockReturnValueOnce(
// @ts-expect-error we need to return an incompatible type to use the testScheduler here
- of({ body: createNodes('5.1.0', '5.2.0', '5.0.0') }).pipe(delay(100))
+ of(createNodes('5.1.0', '5.2.0', '5.0.0')).pipe(delay(100))
);
internalClient.nodes.info.mockReturnValueOnce(
// @ts-expect-error we need to return an incompatible type to use the testScheduler here
- of({ body: createNodes('5.1.1', '5.2.0', '5.0.0') }).pipe(delay(100))
+ of(createNodes('5.1.1', '5.2.0', '5.0.0')).pipe(delay(100))
);
const esNodesCompatibility$ = pollEsNodesVersion({
diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.ts
index b21c3544afa9a..5a1856b35acd6 100644
--- a/src/core/server/elasticsearch/version_check/ensure_es_version.ts
+++ b/src/core/server/elasticsearch/version_check/ensure_es_version.ts
@@ -120,6 +120,7 @@ export function mapNodesVersionCompatibility(
kibanaVersion,
};
}
+
// Returns true if NodesVersionCompatibility nodesInfoRequestError is the same
function compareNodesInfoErrorMessages(
prev: NodesVersionCompatibility,
@@ -127,6 +128,7 @@ function compareNodesInfoErrorMessages(
): boolean {
return prev.nodesInfoRequestError?.message === curr.nodesInfoRequestError?.message;
}
+
// Returns true if two NodesVersionCompatibility entries match
function compareNodes(prev: NodesVersionCompatibility, curr: NodesVersionCompatibility) {
const nodesEqual = (n: NodeInfo, m: NodeInfo) => n.ip === m.ip && n.version === m.version;
@@ -152,11 +154,10 @@ export const pollEsNodesVersion = ({
return timer(0, healthCheckInterval).pipe(
exhaustMap(() => {
return from(
- internalClient.nodes.info({
+ internalClient.nodes.info({
filter_path: ['nodes.*.version', 'nodes.*.http.publish_address', 'nodes.*.ip'],
})
).pipe(
- map(({ body }) => body),
catchError((nodesInfoRequestError) => {
return of({ nodes: {}, nodesInfoRequestError });
})
diff --git a/src/core/server/execution_context/integration_tests/tracing.test.ts b/src/core/server/execution_context/integration_tests/tracing.test.ts
index 7a54315204a6b..4aef2e815fa30 100644
--- a/src/core/server/execution_context/integration_tests/tracing.test.ts
+++ b/src/core/server/execution_context/integration_tests/tracing.test.ts
@@ -58,7 +58,10 @@ describe('trace', () => {
const router = createRouter('');
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
- const { headers } = await context.core.elasticsearch.client.asInternalUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asInternalUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -80,7 +83,10 @@ describe('trace', () => {
const router = createRouter('');
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -102,7 +108,10 @@ describe('trace', () => {
const router = createRouter('');
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
- const { headers } = await context.core.elasticsearch.client.asInternalUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asInternalUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -120,7 +129,10 @@ describe('trace', () => {
const router = createRouter('');
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -142,6 +154,7 @@ describe('trace', () => {
{},
{
opaqueId: 'new-opaque-id',
+ meta: true,
}
);
return res.ok({ body: headers || {} });
@@ -183,7 +196,10 @@ describe('trace', () => {
const router = createRouter('');
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -206,7 +222,10 @@ describe('trace', () => {
const router = createRouter('');
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
executionContext.set(parentContext);
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({
body: {
context: executionContext.get()?.toJSON(),
@@ -319,7 +338,10 @@ describe('trace', () => {
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
executionContext.set(parentContext);
await delay(id-- * 100);
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -429,7 +451,10 @@ describe('trace', () => {
const router = createRouter('');
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -450,7 +475,10 @@ describe('trace', () => {
const router = createRouter('');
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
- const { headers } = await context.core.elasticsearch.client.asInternalUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asInternalUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -471,7 +499,10 @@ describe('trace', () => {
const router = createRouter('');
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -494,7 +525,10 @@ describe('trace', () => {
const router = createRouter('');
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
executionContext.set(parentContext);
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -523,7 +557,10 @@ describe('trace', () => {
};
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
executionContext.set(ctx);
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
+ {},
+ { meta: true }
+ );
return res.ok({ body: headers || {} });
});
@@ -591,7 +628,7 @@ describe('trace', () => {
};
router.get({ path: '/execution-context', validate: false }, async (context, req, res) => {
const { headers } = await executionContext.withContext(newContext, () =>
- context.core.elasticsearch.client.asCurrentUser.ping()
+ context.core.elasticsearch.client.asCurrentUser.ping({}, { meta: true })
);
return res.ok({ body: headers || {} });
});
diff --git a/src/core/server/http/integration_tests/core_services.test.ts b/src/core/server/http/integration_tests/core_services.test.ts
index 4bf64a96cf773..8bf0908ae4dc7 100644
--- a/src/core/server/http/integration_tests/core_services.test.ts
+++ b/src/core/server/http/integration_tests/core_services.test.ts
@@ -297,7 +297,9 @@ describe('http service', () => {
const router = createRouter('/new-platform');
router.get({ path: '/', validate: false }, async (context, req, res) => {
try {
- const result = await elasticsearch.client.asScoped(req).asInternalUser.ping();
+ const result = await elasticsearch.client
+ .asScoped(req)
+ .asInternalUser.ping({}, { meta: true });
return res.ok({
body: result,
});
diff --git a/src/core/server/mocks.ts b/src/core/server/mocks.ts
index 515f5bdb28586..32c0729dcae34 100644
--- a/src/core/server/mocks.ts
+++ b/src/core/server/mocks.ts
@@ -63,6 +63,8 @@ export { deprecationsServiceMock } from './deprecations/deprecations_service.moc
export { executionContextServiceMock } from './execution_context/execution_context_service.mock';
export { docLinksServiceMock } from './doc_links/doc_links_service.mock';
+export type { ElasticsearchClientMock } from './elasticsearch/client/mocks';
+
type MockedPluginInitializerConfig = jest.Mocked['config']>;
export function pluginInitializerContextConfigMock(config: T) {
diff --git a/src/core/server/saved_objects/deprecations/unknown_object_types.test.ts b/src/core/server/saved_objects/deprecations/unknown_object_types.test.ts
index 5b2687262ab36..749ec58bcbfed 100644
--- a/src/core/server/saved_objects/deprecations/unknown_object_types.test.ts
+++ b/src/core/server/saved_objects/deprecations/unknown_object_types.test.ts
@@ -48,9 +48,7 @@ describe('unknown saved object types deprecation', () => {
describe('getUnknownTypesDeprecations', () => {
beforeEach(() => {
- esClient.asInternalUser.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(createSearchResponse(0))
- );
+ esClient.asInternalUser.search.mockResponse(createSearchResponse(0));
});
it('calls `esClient.asInternalUser.search` with the correct parameters', async () => {
@@ -76,9 +74,7 @@ describe('unknown saved object types deprecation', () => {
});
it('returns no deprecation if no unknown type docs are found', async () => {
- esClient.asInternalUser.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(createSearchResponse(0))
- );
+ esClient.asInternalUser.search.mockResponse(createSearchResponse(0));
const deprecations = await getUnknownTypesDeprecations({
esClient,
@@ -91,9 +87,7 @@ describe('unknown saved object types deprecation', () => {
});
it('returns a deprecation if any unknown type docs are found', async () => {
- esClient.asInternalUser.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(createSearchResponse(1))
- );
+ esClient.asInternalUser.search.mockResponse(createSearchResponse(1));
const deprecations = await getUnknownTypesDeprecations({
esClient,
diff --git a/src/core/server/saved_objects/deprecations/unknown_object_types.ts b/src/core/server/saved_objects/deprecations/unknown_object_types.ts
index 8815065984a27..28dbc4dcd41fa 100644
--- a/src/core/server/saved_objects/deprecations/unknown_object_types.ts
+++ b/src/core/server/saved_objects/deprecations/unknown_object_types.ts
@@ -74,7 +74,7 @@ const getUnknownSavedObjects = async ({
});
const query = getUnknownTypesQuery(knownTypes);
- const { body } = await esClient.asInternalUser.search({
+ const body = await esClient.asInternalUser.search({
index: targetIndices,
body: {
size: 10000,
diff --git a/src/core/server/saved_objects/migrations/actions/bulk_overwrite_transformed_documents.test.ts b/src/core/server/saved_objects/migrations/actions/bulk_overwrite_transformed_documents.test.ts
index 57a1f54925d47..7f2cfa01ec42f 100644
--- a/src/core/server/saved_objects/migrations/actions/bulk_overwrite_transformed_documents.test.ts
+++ b/src/core/server/saved_objects/migrations/actions/bulk_overwrite_transformed_documents.test.ts
@@ -21,7 +21,7 @@ describe('bulkOverwriteTransformedDocuments', () => {
it('resolves with `right:bulk_index_succeeded` if no error is encountered', async () => {
const client = elasticsearchClientMock.createInternalClient(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ Promise.resolve({
items: [
{
index: {
@@ -52,7 +52,7 @@ describe('bulkOverwriteTransformedDocuments', () => {
it('resolves with `right:bulk_index_succeeded` if version conflict errors are encountered', async () => {
const client = elasticsearchClientMock.createInternalClient(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ Promise.resolve({
items: [
{
index: {
@@ -113,7 +113,7 @@ describe('bulkOverwriteTransformedDocuments', () => {
it('resolves with `left:target_index_had_write_block` if all errors are write block exceptions', async () => {
const client = elasticsearchClientMock.createInternalClient(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ Promise.resolve({
items: [
{
index: {
@@ -158,7 +158,7 @@ describe('bulkOverwriteTransformedDocuments', () => {
});
const client = elasticsearchClientMock.createInternalClient(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ Promise.resolve({
items: [
{
index: {
diff --git a/src/core/server/saved_objects/migrations/actions/bulk_overwrite_transformed_documents.ts b/src/core/server/saved_objects/migrations/actions/bulk_overwrite_transformed_documents.ts
index f3ddc0c308970..5f3e95bbcfc72 100644
--- a/src/core/server/saved_objects/migrations/actions/bulk_overwrite_transformed_documents.ts
+++ b/src/core/server/saved_objects/migrations/actions/bulk_overwrite_transformed_documents.ts
@@ -93,7 +93,7 @@ export const bulkOverwriteTransformedDocuments =
.then((res) => {
// Filter out version_conflict_engine_exception since these just mean
// that another instance already updated these documents
- const errors: estypes.ErrorCause[] = (res.body.items ?? [])
+ const errors: estypes.ErrorCause[] = (res.items ?? [])
.filter((item) => item.index?.error)
.map((item) => item.index!.error!)
.filter(({ type }) => type !== 'version_conflict_engine_exception');
diff --git a/src/core/server/saved_objects/migrations/actions/calculate_exclude_filters.ts b/src/core/server/saved_objects/migrations/actions/calculate_exclude_filters.ts
index 2b35e3b59e988..27ce7bd4c404b 100644
--- a/src/core/server/saved_objects/migrations/actions/calculate_exclude_filters.ts
+++ b/src/core/server/saved_objects/migrations/actions/calculate_exclude_filters.ts
@@ -45,7 +45,11 @@ export const calculateExcludeFilters =
Object.entries(excludeFromUpgradeFilterHooks).map(([soType, hook]) =>
withTimeout({
promise: Promise.resolve(
- hook({ readonlyEsClient: { search: client.search.bind(client) } })
+ hook({
+ readonlyEsClient: {
+ search: client.search.bind(client) as ElasticsearchClient['search'],
+ },
+ })
),
timeoutMs: hookTimeoutMs,
})
diff --git a/src/core/server/saved_objects/migrations/actions/check_for_unknown_docs.test.ts b/src/core/server/saved_objects/migrations/actions/check_for_unknown_docs.test.ts
index 0ddb858f91bc0..4254c152a1fa8 100644
--- a/src/core/server/saved_objects/migrations/actions/check_for_unknown_docs.test.ts
+++ b/src/core/server/saved_objects/migrations/actions/check_for_unknown_docs.test.ts
@@ -53,7 +53,7 @@ describe('checkForUnknownDocs', () => {
it('calls `client.search` with the correct parameters', async () => {
const client = elasticsearchClientMock.createInternalClient(
- elasticsearchClientMock.createSuccessTransportRequestPromise({ hits: { hits: [] } })
+ Promise.resolve({ hits: { hits: [] } })
);
const task = checkForUnknownDocs({
@@ -85,7 +85,7 @@ describe('checkForUnknownDocs', () => {
it('resolves with `Either.right` when no unknown docs are found', async () => {
const client = elasticsearchClientMock.createInternalClient(
- elasticsearchClientMock.createSuccessTransportRequestPromise({ hits: { hits: [] } })
+ Promise.resolve({ hits: { hits: [] } })
);
const task = checkForUnknownDocs({
@@ -103,7 +103,7 @@ describe('checkForUnknownDocs', () => {
it('resolves with `Either.left` when unknown docs are found', async () => {
const client = elasticsearchClientMock.createInternalClient(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ Promise.resolve({
hits: {
hits: [
{ _id: '12', _source: { type: 'foo' } },
@@ -134,7 +134,7 @@ describe('checkForUnknownDocs', () => {
it('uses `unknown` as the type when the document does not contain a type field', async () => {
const client = elasticsearchClientMock.createInternalClient(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ Promise.resolve({
hits: {
hits: [{ _id: '12', _source: {} }],
},
diff --git a/src/core/server/saved_objects/migrations/actions/check_for_unknown_docs.ts b/src/core/server/saved_objects/migrations/actions/check_for_unknown_docs.ts
index 6dd8fbda73c95..f9e3df9a0443a 100644
--- a/src/core/server/saved_objects/migrations/actions/check_for_unknown_docs.ts
+++ b/src/core/server/saved_objects/migrations/actions/check_for_unknown_docs.ts
@@ -56,8 +56,8 @@ export const checkForUnknownDocs =
query,
},
})
- .then((response) => {
- const { hits } = response.body.hits;
+ .then((body) => {
+ const { hits } = body.hits;
if (hits.length) {
return Either.left({
type: 'unknown_docs_found' as const,
diff --git a/src/core/server/saved_objects/migrations/actions/clone_index.ts b/src/core/server/saved_objects/migrations/actions/clone_index.ts
index d7994f5a465d2..e77ce8c47156f 100644
--- a/src/core/server/saved_objects/migrations/actions/clone_index.ts
+++ b/src/core/server/saved_objects/migrations/actions/clone_index.ts
@@ -83,7 +83,7 @@ export const cloneIndex = ({
},
{ maxRetries: 0 /** handle retry ourselves for now */ }
)
- .then((res) => {
+ .then((response) => {
/**
* - acknowledged=false, we timed out before the cluster state was
* updated with the newly created index, but it probably will be
@@ -93,8 +93,8 @@ export const cloneIndex = ({
* - acknowledged=true, shards_acknowledged=true, cloning complete
*/
return Either.right({
- acknowledged: res.body.acknowledged,
- shardsAcknowledged: res.body.shards_acknowledged,
+ acknowledged: response.acknowledged,
+ shardsAcknowledged: response.shards_acknowledged,
});
})
.catch((error: EsErrors.ResponseError) => {
diff --git a/src/core/server/saved_objects/migrations/actions/close_pit.ts b/src/core/server/saved_objects/migrations/actions/close_pit.ts
index 9dd7f1d22386f..cb340068560d4 100644
--- a/src/core/server/saved_objects/migrations/actions/close_pit.ts
+++ b/src/core/server/saved_objects/migrations/actions/close_pit.ts
@@ -31,7 +31,7 @@ export const closePit =
body: { id: pitId },
})
.then((response) => {
- if (!response.body.succeeded) {
+ if (!response.succeeded) {
throw new Error(`Failed to close PointInTime with id: ${pitId}`);
}
return Either.right({});
diff --git a/src/core/server/saved_objects/migrations/actions/create_index.ts b/src/core/server/saved_objects/migrations/actions/create_index.ts
index b687a4ad93b36..e037de1712373 100644
--- a/src/core/server/saved_objects/migrations/actions/create_index.ts
+++ b/src/core/server/saved_objects/migrations/actions/create_index.ts
@@ -102,8 +102,8 @@ export const createIndex = ({
* - acknowledged=true, shards_acknowledged=true, index creation complete
*/
return Either.right({
- acknowledged: Boolean(res.body.acknowledged),
- shardsAcknowledged: res.body.shards_acknowledged,
+ acknowledged: Boolean(res.acknowledged),
+ shardsAcknowledged: res.shards_acknowledged,
});
})
.catch((error) => {
diff --git a/src/core/server/saved_objects/migrations/actions/fetch_indices.ts b/src/core/server/saved_objects/migrations/actions/fetch_indices.ts
index 1256b2d858906..faed825400c1f 100644
--- a/src/core/server/saved_objects/migrations/actions/fetch_indices.ts
+++ b/src/core/server/saved_objects/migrations/actions/fetch_indices.ts
@@ -43,7 +43,7 @@ export const fetchIndices =
},
{ ignore: [404], maxRetries: 0 }
)
- .then(({ body }) => {
+ .then((body) => {
return Either.right(body);
})
.catch(catchRetryableEsClientErrors);
diff --git a/src/core/server/saved_objects/migrations/actions/integration_tests/actions.test.ts b/src/core/server/saved_objects/migrations/actions/integration_tests/actions.test.ts
index 008bc3d301d9f..ef84f0cb49231 100644
--- a/src/core/server/saved_objects/migrations/actions/integration_tests/actions.test.ts
+++ b/src/core/server/saved_objects/migrations/actions/integration_tests/actions.test.ts
@@ -63,7 +63,7 @@ describe('migration actions', () => {
beforeAll(async () => {
esServer = await startES();
- client = esServer.es.getKibanaEsClient();
+ client = esServer.es.getClient();
// Create test fixture data:
await createIndex({
@@ -277,7 +277,7 @@ describe('migration actions', () => {
})();
const redStatusResponse = await client.cluster.health({ index: 'red_then_yellow_index' });
- expect(redStatusResponse.body.status).toBe('red');
+ expect(redStatusResponse.status).toBe('red');
client.indices.putSettings({
index: 'red_then_yellow_index',
@@ -291,7 +291,7 @@ describe('migration actions', () => {
// Assert that the promise didn't resolve before the index became yellow
const yellowStatusResponse = await client.cluster.health({ index: 'red_then_yellow_index' });
- expect(yellowStatusResponse.body.status).toBe('yellow');
+ expect(yellowStatusResponse.status).toBe('yellow');
});
});
@@ -924,7 +924,7 @@ describe('migration actions', () => {
},
});
- await expect(searchResponse.body.hits.hits.length).toBeGreaterThan(0);
+ await expect(searchResponse.hits.hits.length).toBeGreaterThan(0);
});
it('rejects if index does not exist', async () => {
const openPitTask = openPit({ client, index: 'no_such_index' });
diff --git a/src/core/server/saved_objects/migrations/actions/integration_tests/es_errors.test.ts b/src/core/server/saved_objects/migrations/actions/integration_tests/es_errors.test.ts
index 2473d8d3ae410..7f998938e92c0 100644
--- a/src/core/server/saved_objects/migrations/actions/integration_tests/es_errors.test.ts
+++ b/src/core/server/saved_objects/migrations/actions/integration_tests/es_errors.test.ts
@@ -65,7 +65,7 @@ describe('Elasticsearch Errors', () => {
);
// @ts-expect-error @elastic/elasticsearch doesn't declare error on IndexResponse
- expect(isWriteBlockException(res.body.error!)).toEqual(true);
+ expect(isWriteBlockException(res.error!)).toEqual(true);
});
it('correctly identify errors from create operations', async () => {
@@ -81,7 +81,7 @@ describe('Elasticsearch Errors', () => {
);
// @ts-expect-error @elastic/elasticsearch doesn't declare error on IndexResponse
- expect(isWriteBlockException(res.body.error!)).toEqual(true);
+ expect(isWriteBlockException(res.error!)).toEqual(true);
});
it('correctly identify errors from bulk index operations', async () => {
@@ -100,7 +100,7 @@ describe('Elasticsearch Errors', () => {
],
});
- const cause = res.body.items[0].index!.error! as estypes.ErrorCause;
+ const cause = res.items[0].index!.error! as estypes.ErrorCause;
expect(isWriteBlockException(cause)).toEqual(true);
});
@@ -122,7 +122,7 @@ describe('Elasticsearch Errors', () => {
],
});
- const cause = res.body.items[0].create!.error! as estypes.ErrorCause;
+ const cause = res.items[0].create!.error! as estypes.ErrorCause;
expect(isWriteBlockException(cause)).toEqual(true);
});
diff --git a/src/core/server/saved_objects/migrations/actions/open_pit.ts b/src/core/server/saved_objects/migrations/actions/open_pit.ts
index 43c84a2b26613..7e1f3a77f2d1e 100644
--- a/src/core/server/saved_objects/migrations/actions/open_pit.ts
+++ b/src/core/server/saved_objects/migrations/actions/open_pit.ts
@@ -40,6 +40,6 @@ export const openPit =
index,
keep_alive: pitKeepAlive,
})
- .then((response) => Either.right({ pitId: response.body.id }))
+ .then((response) => Either.right({ pitId: response.id }))
.catch(catchRetryableEsClientErrors);
};
diff --git a/src/core/server/saved_objects/migrations/actions/pickup_updated_mappings.ts b/src/core/server/saved_objects/migrations/actions/pickup_updated_mappings.ts
index 2db6b1833c6dd..c1e1111a4afe3 100644
--- a/src/core/server/saved_objects/migrations/actions/pickup_updated_mappings.ts
+++ b/src/core/server/saved_objects/migrations/actions/pickup_updated_mappings.ts
@@ -14,6 +14,7 @@ import {
RetryableEsClientError,
} from './catch_retryable_es_client_errors';
import { BATCH_SIZE } from './constants';
+
export interface UpdateByQueryResponse {
taskId: string;
}
@@ -52,7 +53,7 @@ export const pickupUpdatedMappings =
// Create a task and return task id instead of blocking until complete
wait_for_completion: false,
})
- .then(({ body: { task: taskId } }) => {
+ .then(({ task: taskId }) => {
return Either.right({ taskId: String(taskId!) });
})
.catch(catchRetryableEsClientErrors);
diff --git a/src/core/server/saved_objects/migrations/actions/read_with_pit.ts b/src/core/server/saved_objects/migrations/actions/read_with_pit.ts
index 0902e206147d3..013cd59271ee1 100644
--- a/src/core/server/saved_objects/migrations/actions/read_with_pit.ts
+++ b/src/core/server/saved_objects/migrations/actions/read_with_pit.ts
@@ -68,12 +68,12 @@ export const readWithPit =
query,
},
})
- .then((response) => {
+ .then((body) => {
const totalHits =
- typeof response.body.hits.total === 'number'
- ? response.body.hits.total // This format is to be removed in 8.0
- : response.body.hits.total?.value;
- const hits = response.body.hits.hits;
+ typeof body.hits.total === 'number'
+ ? body.hits.total // This format is to be removed in 8.0
+ : body.hits.total?.value;
+ const hits = body.hits.hits;
if (hits.length > 0) {
return Either.right({
diff --git a/src/core/server/saved_objects/migrations/actions/reindex.ts b/src/core/server/saved_objects/migrations/actions/reindex.ts
index e8e054c7a1780..cfd7449971b7f 100644
--- a/src/core/server/saved_objects/migrations/actions/reindex.ts
+++ b/src/core/server/saved_objects/migrations/actions/reindex.ts
@@ -21,6 +21,7 @@ import { BATCH_SIZE } from './constants';
export interface ReindexResponse {
taskId: string;
}
+
/** @internal */
export interface ReindexParams {
client: ElasticsearchClient;
@@ -34,6 +35,7 @@ export interface ReindexParams {
*/
unusedTypesQuery: estypes.QueryDslQueryContainer;
}
+
/**
* Reindex documents from the `sourceIndex` into the `targetIndex`. Returns a
* task ID which can be tracked for progress.
@@ -85,7 +87,7 @@ export const reindex =
// Create a task and return task id instead of blocking until complete
wait_for_completion: false,
})
- .then(({ body: { task: taskId } }) => {
+ .then(({ task: taskId }) => {
return Either.right({ taskId: String(taskId) });
})
.catch(catchRetryableEsClientErrors);
diff --git a/src/core/server/saved_objects/migrations/actions/remove_write_block.ts b/src/core/server/saved_objects/migrations/actions/remove_write_block.ts
index cca9ea5e7598e..47a3ecf7a4404 100644
--- a/src/core/server/saved_objects/migrations/actions/remove_write_block.ts
+++ b/src/core/server/saved_objects/migrations/actions/remove_write_block.ts
@@ -19,6 +19,7 @@ export interface RemoveWriteBlockParams {
client: ElasticsearchClient;
index: string;
}
+
/**
* Removes a write block from an index
*/
@@ -32,10 +33,7 @@ export const removeWriteBlock =
> =>
() => {
return client.indices
- .putSettings<{
- acknowledged: boolean;
- shards_acknowledged: boolean;
- }>(
+ .putSettings(
{
index,
// Don't change any existing settings
@@ -49,7 +47,7 @@ export const removeWriteBlock =
{ maxRetries: 0 /** handle retry ourselves for now */ }
)
.then((res) => {
- return res.body.acknowledged === true
+ return res.acknowledged === true
? Either.right('remove_write_block_succeeded' as const)
: Either.left({
type: 'retryable_es_client_error' as const,
diff --git a/src/core/server/saved_objects/migrations/actions/search_for_outdated_documents.ts b/src/core/server/saved_objects/migrations/actions/search_for_outdated_documents.ts
index 5a92a7c6cc286..bc6b6e5c29d46 100644
--- a/src/core/server/saved_objects/migrations/actions/search_for_outdated_documents.ts
+++ b/src/core/server/saved_objects/migrations/actions/search_for_outdated_documents.ts
@@ -73,7 +73,7 @@ export const searchForOutdatedDocuments =
],
})
.then((res) =>
- Either.right({ outdatedDocuments: (res.body.hits?.hits as SavedObjectsRawDoc[]) ?? [] })
+ Either.right({ outdatedDocuments: (res.hits?.hits as SavedObjectsRawDoc[]) ?? [] })
)
.catch(catchRetryableEsClientErrors);
};
diff --git a/src/core/server/saved_objects/migrations/actions/set_write_block.ts b/src/core/server/saved_objects/migrations/actions/set_write_block.ts
index 9c40e1b64fae0..eaca12ab7e315 100644
--- a/src/core/server/saved_objects/migrations/actions/set_write_block.ts
+++ b/src/core/server/saved_objects/migrations/actions/set_write_block.ts
@@ -21,6 +21,7 @@ export interface SetWriteBlockParams {
client: ElasticsearchClient;
index: string;
}
+
/**
* Sets a write block in place for the given index. If the response includes
* `acknowledged: true` all in-progress writes have drained and no further
@@ -41,10 +42,7 @@ export const setWriteBlock =
() => {
return (
client.indices
- .addBlock<{
- acknowledged: boolean;
- shards_acknowledged: boolean;
- }>(
+ .addBlock(
{
index,
block: 'write',
@@ -52,8 +50,8 @@ export const setWriteBlock =
{ maxRetries: 0 /** handle retry ourselves for now */ }
)
// not typed yet
- .then((res: any) => {
- return res.body.acknowledged === true
+ .then((res) => {
+ return res.acknowledged === true
? Either.right('set_write_block_succeeded' as const)
: Either.left({
type: 'retryable_es_client_error' as const,
diff --git a/src/core/server/saved_objects/migrations/actions/update_and_pickup_mappings.ts b/src/core/server/saved_objects/migrations/actions/update_and_pickup_mappings.ts
index 8c742005a01ce..06b3e9051ffa3 100644
--- a/src/core/server/saved_objects/migrations/actions/update_and_pickup_mappings.ts
+++ b/src/core/server/saved_objects/migrations/actions/update_and_pickup_mappings.ts
@@ -51,7 +51,7 @@ export const updateAndPickupMappings = ({
timeout: DEFAULT_TIMEOUT,
body: mappings,
})
- .then((res) => {
+ .then(() => {
// Ignore `acknowledged: false`. When the coordinating node accepts
// the new cluster state update but not all nodes have applied the
// update within the timeout `acknowledged` will be false. However,
diff --git a/src/core/server/saved_objects/migrations/actions/verify_reindex.ts b/src/core/server/saved_objects/migrations/actions/verify_reindex.ts
index a344bf5a97ff3..481daf459251d 100644
--- a/src/core/server/saved_objects/migrations/actions/verify_reindex.ts
+++ b/src/core/server/saved_objects/migrations/actions/verify_reindex.ts
@@ -33,13 +33,13 @@ export const verifyReindex =
() => {
const count = (index: string) =>
client
- .count<{ count: number }>({
+ .count({
index,
// Return an error when targeting missing or closed indices
allow_no_indices: false,
})
.then((res) => {
- return res.body.count;
+ return res.count;
});
return Promise.all([count(sourceIndex), count(targetIndex)])
diff --git a/src/core/server/saved_objects/migrations/actions/wait_for_index_status_yellow.ts b/src/core/server/saved_objects/migrations/actions/wait_for_index_status_yellow.ts
index 676471d99b7d2..dbff85ff59c23 100644
--- a/src/core/server/saved_objects/migrations/actions/wait_for_index_status_yellow.ts
+++ b/src/core/server/saved_objects/migrations/actions/wait_for_index_status_yellow.ts
@@ -51,7 +51,7 @@ export const waitForIndexStatusYellow =
{ ignore: [408] }
)
.then((res) => {
- if (res.body.timed_out === true) {
+ if (res.timed_out === true) {
return Either.left({
type: 'retryable_es_client_error' as const,
message: `Timeout waiting for the status of the [${index}] index to become 'yellow'`,
diff --git a/src/core/server/saved_objects/migrations/actions/wait_for_task.ts b/src/core/server/saved_objects/migrations/actions/wait_for_task.ts
index 1a319d17dbce9..f3f1e116ab3c0 100644
--- a/src/core/server/saved_objects/migrations/actions/wait_for_task.ts
+++ b/src/core/server/saved_objects/migrations/actions/wait_for_task.ts
@@ -82,8 +82,7 @@ export const waitForTask =
wait_for_completion: true,
timeout,
})
- .then((res) => {
- const body = res.body;
+ .then((body) => {
const failures = body.response?.failures ?? [];
return Either.right({
completed: body.completed,
diff --git a/src/core/server/saved_objects/migrations/integration_tests/7.7.2_xpack_100k.test.ts b/src/core/server/saved_objects/migrations/integration_tests/7.7.2_xpack_100k.test.ts
index 79a49b2518092..1b96baf210531 100644
--- a/src/core/server/saved_objects/migrations/integration_tests/7.7.2_xpack_100k.test.ts
+++ b/src/core/server/saved_objects/migrations/integration_tests/7.7.2_xpack_100k.test.ts
@@ -122,6 +122,6 @@ describe('migration from 7.7.2-xpack with 100k objects', () => {
// Use a >= comparison since once Kibana has started it might create new
// documents like telemetry tasks
- expect(migratedIndexResponse.body.count).toBeGreaterThanOrEqual(oldIndexResponse.body.count);
+ expect(migratedIndexResponse.count).toBeGreaterThanOrEqual(oldIndexResponse.count);
});
});
diff --git a/src/core/server/saved_objects/migrations/integration_tests/7_13_0_failed_action_tasks.test.ts b/src/core/server/saved_objects/migrations/integration_tests/7_13_0_failed_action_tasks.test.ts
index 48bcdd6e5eaca..d2bf71f023de7 100644
--- a/src/core/server/saved_objects/migrations/integration_tests/7_13_0_failed_action_tasks.test.ts
+++ b/src/core/server/saved_objects/migrations/integration_tests/7_13_0_failed_action_tasks.test.ts
@@ -55,7 +55,7 @@ describe('migration from 7.13 to 7.14+ with many failed action_tasks', () => {
kibanaIndexName = '.kibana',
taskManagerIndexName = '.kibana_task_manager'
): Promise<{ tasksCount: number; actionTaskParamsCount: number }> => {
- const esClient: ElasticsearchClient = esServer.es.getKibanaEsClient();
+ const esClient: ElasticsearchClient = esServer.es.getClient();
const actionTaskParamsResponse = await esClient.count({
index: kibanaIndexName,
@@ -75,8 +75,8 @@ describe('migration from 7.13 to 7.14+ with many failed action_tasks', () => {
});
return {
- actionTaskParamsCount: actionTaskParamsResponse.body.count,
- tasksCount: tasksResponse.body.count,
+ actionTaskParamsCount: actionTaskParamsResponse.count,
+ tasksCount: tasksResponse.count,
};
};
diff --git a/src/core/server/saved_objects/migrations/integration_tests/batch_size_bytes.test.ts b/src/core/server/saved_objects/migrations/integration_tests/batch_size_bytes.test.ts
index a86177b59ee3b..e9915b9fc9759 100644
--- a/src/core/server/saved_objects/migrations/integration_tests/batch_size_bytes.test.ts
+++ b/src/core/server/saved_objects/migrations/integration_tests/batch_size_bytes.test.ts
@@ -31,7 +31,7 @@ function sortByTypeAndId(a: { type: string; id: string }, b: { type: string; id:
}
async function fetchDocuments(esClient: ElasticsearchClient, index: string) {
- const { body } = await esClient.search({
+ const body = await esClient.search({
index,
body: {
query: {
@@ -95,7 +95,7 @@ describe('migration v2', () => {
// wait a bit for the count to settle.
await new Promise((resolve) => setTimeout(resolve, 5000));
- const esClient: ElasticsearchClient = esServer.es.getKibanaEsClient();
+ const esClient: ElasticsearchClient = esServer.es.getClient();
// assert that the docs from the original index have been migrated rather than comparing a doc count after startup
const originalDocs = await fetchDocuments(esClient, '.kibana_7.14.0_001');
diff --git a/src/core/server/saved_objects/migrations/integration_tests/cleanup.test.ts b/src/core/server/saved_objects/migrations/integration_tests/cleanup.test.ts
index 4f3026c619d3c..c84f72b184261 100644
--- a/src/core/server/saved_objects/migrations/integration_tests/cleanup.test.ts
+++ b/src/core/server/saved_objects/migrations/integration_tests/cleanup.test.ts
@@ -133,7 +133,7 @@ describe('migration v2', () => {
const pitId = logRecordWithPit.right.pitId;
expect(pitId).toBeTruthy();
- const client = esServer.es.getKibanaEsClient();
+ const client = esServer.es.getClient();
await expect(
client.search({
body: {
diff --git a/src/core/server/saved_objects/migrations/integration_tests/migration_from_older_v1.test.ts b/src/core/server/saved_objects/migrations/integration_tests/migration_from_older_v1.test.ts
index 8c71cf3a29ef5..e0c8aa340bd2a 100644
--- a/src/core/server/saved_objects/migrations/integration_tests/migration_from_older_v1.test.ts
+++ b/src/core/server/saved_objects/migrations/integration_tests/migration_from_older_v1.test.ts
@@ -35,7 +35,7 @@ function sortByTypeAndId(a: { type: string; id: string }, b: { type: string; id:
}
async function fetchDocuments(esClient: ElasticsearchClient, index: string) {
- const { body } = await esClient.search({
+ const body = await esClient.search({
index,
body: {
query: {
@@ -175,7 +175,7 @@ describe('migrating from 7.3.0-xpack which used v1 migrations', () => {
});
it('creates the new index and the correct aliases', async () => {
- const { body } = await esClient.indices.get(
+ const body = await esClient.indices.get(
{
index: migratedIndex,
},
@@ -203,7 +203,7 @@ describe('migrating from 7.3.0-xpack which used v1 migrations', () => {
},
size: 10000,
});
- const allDocuments = res.body.hits.hits as SavedObjectsRawDoc[];
+ const allDocuments = res.hits.hits as SavedObjectsRawDoc[];
allDocuments.forEach((doc) => {
assertMigrationVersion(doc, expectedVersions);
});
diff --git a/src/core/server/saved_objects/migrations/integration_tests/migration_from_same_v1.test.ts b/src/core/server/saved_objects/migrations/integration_tests/migration_from_same_v1.test.ts
index 1fa739768e412..eb54683e3a457 100644
--- a/src/core/server/saved_objects/migrations/integration_tests/migration_from_same_v1.test.ts
+++ b/src/core/server/saved_objects/migrations/integration_tests/migration_from_same_v1.test.ts
@@ -35,7 +35,7 @@ function sortByTypeAndId(a: { type: string; id: string }, b: { type: string; id:
}
async function fetchDocuments(esClient: ElasticsearchClient, index: string) {
- const { body } = await esClient.search({
+ const body = await esClient.search({
index,
body: {
query: {
@@ -179,7 +179,7 @@ describe('migrating from the same Kibana version that used v1 migrations', () =>
});
it('creates the new index and the correct aliases', async () => {
- const { body } = await esClient.indices.get(
+ const body = await esClient.indices.get(
{
index: migratedIndex,
},
@@ -206,7 +206,7 @@ describe('migrating from the same Kibana version that used v1 migrations', () =>
},
size: 10000,
});
- const allDocuments = res.body.hits.hits as SavedObjectsRawDoc[];
+ const allDocuments = res.hits.hits as SavedObjectsRawDoc[];
allDocuments.forEach((doc) => {
assertMigrationVersion(doc, expectedVersions);
});
diff --git a/src/core/server/saved_objects/migrations/integration_tests/multiple_es_nodes.test.ts b/src/core/server/saved_objects/migrations/integration_tests/multiple_es_nodes.test.ts
index ae8ae6bcc3084..f88f97a677616 100644
--- a/src/core/server/saved_objects/migrations/integration_tests/multiple_es_nodes.test.ts
+++ b/src/core/server/saved_objects/migrations/integration_tests/multiple_es_nodes.test.ts
@@ -29,7 +29,7 @@ function extractSortNumberFromId(id: string): number {
}
async function fetchDocs(esClient: ElasticsearchClient, index: string, type: string) {
- const { body } = await esClient.search({
+ const body = await esClient.search({
index,
size: 10000,
body: {
@@ -180,7 +180,7 @@ describe('migration v2', () => {
});
await root.start();
- const esClient = esServer.es.getKibanaEsClient();
+ const esClient = esServer.es.getClient();
const migratedFooDocs = await fetchDocs(esClient, migratedIndex, 'foo');
expect(migratedFooDocs.length).toBe(2500);
diff --git a/src/core/server/saved_objects/migrations/integration_tests/multiple_kibana_nodes.test.ts b/src/core/server/saved_objects/migrations/integration_tests/multiple_kibana_nodes.test.ts
index 9830d3bf954cc..bc8c138e9ef20 100644
--- a/src/core/server/saved_objects/migrations/integration_tests/multiple_kibana_nodes.test.ts
+++ b/src/core/server/saved_objects/migrations/integration_tests/multiple_kibana_nodes.test.ts
@@ -30,7 +30,7 @@ function extractSortNumberFromId(id: string): number {
}
async function fetchDocs(esClient: ElasticsearchClient, index: string) {
- const { body } = await esClient.search({
+ const body = await esClient.search({
index,
size: 10000,
body: {
@@ -183,7 +183,7 @@ describe('migration v2', () => {
await startWithDelay([rootA, rootB, rootC], 0);
- const esClient = esServer.es.getKibanaEsClient();
+ const esClient = esServer.es.getClient();
const migratedDocs = await fetchDocs(esClient, migratedIndex);
expect(migratedDocs.length).toBe(5000);
@@ -202,7 +202,7 @@ describe('migration v2', () => {
await startWithDelay([rootA, rootB, rootC], 1);
- const esClient = esServer.es.getKibanaEsClient();
+ const esClient = esServer.es.getClient();
const migratedDocs = await fetchDocs(esClient, migratedIndex);
expect(migratedDocs.length).toBe(5000);
@@ -221,7 +221,7 @@ describe('migration v2', () => {
await startWithDelay([rootA, rootB, rootC], 5);
- const esClient = esServer.es.getKibanaEsClient();
+ const esClient = esServer.es.getClient();
const migratedDocs = await fetchDocs(esClient, migratedIndex);
expect(migratedDocs.length).toBe(5000);
@@ -240,7 +240,7 @@ describe('migration v2', () => {
await startWithDelay([rootA, rootB, rootC], 20);
- const esClient = esServer.es.getKibanaEsClient();
+ const esClient = esServer.es.getClient();
const migratedDocs = await fetchDocs(esClient, migratedIndex);
expect(migratedDocs.length).toBe(5000);
diff --git a/src/core/server/saved_objects/migrations/integration_tests/outdated_docs.test.ts b/src/core/server/saved_objects/migrations/integration_tests/outdated_docs.test.ts
index b40fcda246c3f..c62a764aea653 100644
--- a/src/core/server/saved_objects/migrations/integration_tests/outdated_docs.test.ts
+++ b/src/core/server/saved_objects/migrations/integration_tests/outdated_docs.test.ts
@@ -122,7 +122,7 @@ function createRoot() {
}
async function fetchDocs(esClient: ElasticsearchClient, index: string) {
- const { body } = await esClient.search({
+ const body = await esClient.search({
index,
body: {
query: {
diff --git a/src/core/server/saved_objects/migrations/integration_tests/rewriting_id.test.ts b/src/core/server/saved_objects/migrations/integration_tests/rewriting_id.test.ts
index 79e55ef5beeed..82f7bc5de978e 100644
--- a/src/core/server/saved_objects/migrations/integration_tests/rewriting_id.test.ts
+++ b/src/core/server/saved_objects/migrations/integration_tests/rewriting_id.test.ts
@@ -28,7 +28,7 @@ function sortByTypeAndId(a: { type: string; id: string }, b: { type: string; id:
}
async function fetchDocs(esClient: ElasticsearchClient, index: string) {
- const { body } = await esClient.search({
+ const body = await esClient.search({
index,
body: {
query: {
diff --git a/src/core/server/saved_objects/migrations/kibana_migrator.test.ts b/src/core/server/saved_objects/migrations/kibana_migrator.test.ts
index eb7b72f144031..4bb24a3f8240d 100644
--- a/src/core/server/saved_objects/migrations/kibana_migrator.test.ts
+++ b/src/core/server/saved_objects/migrations/kibana_migrator.test.ts
@@ -97,15 +97,9 @@ describe('KibanaMigrator', () => {
it('throws if prepareMigrations is not called first', async () => {
const options = mockOptions();
- options.client.cat.templates.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise([], { statusCode: 404 })
- );
- options.client.indices.get.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 })
- );
- options.client.indices.getAlias.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 })
- );
+ options.client.cat.templates.mockResponse([], { statusCode: 404 });
+ options.client.indices.get.mockResponse({}, { statusCode: 404 });
+ options.client.indices.getAlias.mockResponse({}, { statusCode: 404 });
const migrator = new KibanaMigrator(options);
@@ -117,12 +111,8 @@ describe('KibanaMigrator', () => {
it('only runs migrations once if called multiple times', async () => {
const options = mockOptions();
- options.client.indices.get.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 })
- );
- options.client.indices.getAlias.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 })
- );
+ options.client.indices.get.mockResponse({}, { statusCode: 404 });
+ options.client.indices.getAlias.mockResponse({}, { statusCode: 404 });
const migrator = new KibanaMigrator(options);
@@ -158,20 +148,18 @@ describe('KibanaMigrator', () => {
});
it('rejects when the migration state machine terminates in a FATAL state', () => {
const options = mockV2MigrationOptions();
- options.client.indices.get.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- {
- '.my-index_8.2.4_001': {
- aliases: {
- '.my-index': {},
- '.my-index_8.2.4': {},
- },
- mappings: { properties: {}, _meta: { migrationMappingPropertyHashes: {} } },
- settings: {},
+ options.client.indices.get.mockResponse(
+ {
+ '.my-index_8.2.4_001': {
+ aliases: {
+ '.my-index': {},
+ '.my-index_8.2.4': {},
},
+ mappings: { properties: {}, _meta: { migrationMappingPropertyHashes: {} } },
+ settings: {},
},
- { statusCode: 200 }
- )
+ },
+ { statusCode: 200 }
);
const migrator = new KibanaMigrator(options);
@@ -183,14 +171,11 @@ describe('KibanaMigrator', () => {
it('rejects when an unexpected exception occurs in an action', async () => {
const options = mockV2MigrationOptions();
- options.client.tasks.get.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- completed: true,
- error: { type: 'elasticsearch_exception', reason: 'task failed with an error' },
- failures: [],
- task: { description: 'task description' } as any,
- })
- );
+ options.client.tasks.get.mockResponse({
+ completed: true,
+ error: { type: 'elasticsearch_exception', reason: 'task failed with an error' },
+ task: { description: 'task description' } as any,
+ });
const migrator = new KibanaMigrator(options);
migrator.prepareMigrations();
@@ -213,56 +198,38 @@ type MockedOptions = KibanaMigratorOptions & {
const mockV2MigrationOptions = () => {
const options = mockOptions();
- options.client.indices.get.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- {
- '.my-index': {
- aliases: { '.kibana': {} },
- mappings: { properties: {} },
- settings: {},
- },
+ options.client.indices.get.mockResponse(
+ {
+ '.my-index': {
+ aliases: { '.kibana': {} },
+ mappings: { properties: {} },
+ settings: {},
},
- { statusCode: 200 }
- )
- );
- options.client.indices.addBlock.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- acknowledged: true,
- shards_acknowledged: true,
- indices: [],
- })
- );
- options.client.reindex.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- taskId: 'reindex_task_id',
- } as estypes.ReindexResponse)
- );
- options.client.tasks.get.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- completed: true,
- error: undefined,
- failures: [],
- task: { description: 'task description' } as any,
- } as estypes.TasksGetResponse)
+ },
+ { statusCode: 200 }
);
+ options.client.indices.addBlock.mockResponse({
+ acknowledged: true,
+ shards_acknowledged: true,
+ indices: [],
+ });
+ options.client.reindex.mockResponse({
+ taskId: 'reindex_task_id',
+ } as estypes.ReindexResponse);
+ options.client.tasks.get.mockResponse({
+ completed: true,
+ error: undefined,
+ failures: [],
+ task: { description: 'task description' } as any,
+ } as estypes.TasksGetResponse);
- options.client.search = jest
- .fn()
- .mockImplementation(() =>
- elasticsearchClientMock.createSuccessTransportRequestPromise({ hits: { hits: [] } })
- );
+ options.client.search.mockResponse({ hits: { hits: [] } } as any);
- options.client.openPointInTime = jest
- .fn()
- .mockImplementation(() =>
- elasticsearchClientMock.createSuccessTransportRequestPromise({ id: 'pit_id' })
- );
+ options.client.openPointInTime.mockResponse({ id: 'pit_id' });
- options.client.closePointInTime = jest
- .fn()
- .mockImplementation(() =>
- elasticsearchClientMock.createSuccessTransportRequestPromise({ succeeded: true })
- );
+ options.client.closePointInTime.mockResponse({
+ succeeded: true,
+ } as estypes.ClosePointInTimeResponse);
return options;
};
diff --git a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts
index 052096adcc853..202b5ca4386c9 100644
--- a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts
+++ b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts
@@ -11,9 +11,6 @@ import {
mockRawDocExistsInNamespace,
} from './collect_multi_namespace_references.test.mock';
-import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
-
-import type { ElasticsearchClient } from '../../../elasticsearch';
import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks';
import { typeRegistryMock } from '../../saved_objects_type_registry.mock';
import { SavedObjectsSerializer } from '../../serialization';
@@ -43,7 +40,7 @@ beforeEach(() => {
});
describe('collectMultiNamespaceReferences', () => {
- let client: DeeplyMockedKeys;
+ let client: ReturnType;
/** Sets up the type registry, saved objects client, etc. and return the full parameters object to be passed to `collectMultiNamespaceReferences` */
function setup(
@@ -88,30 +85,28 @@ describe('collectMultiNamespaceReferences', () => {
references?: Array<{ type: string; id: string }>;
}>
) {
- client.mget.mockReturnValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- docs: results.map((x) => {
- const references =
- x.references?.map(({ type, id }) => ({ type, id, name: 'ref-name' })) ?? [];
- return x.found
- ? {
- _id: 'doesnt-matter',
- _index: 'doesnt-matter',
- _source: {
- namespaces: SPACES,
- references,
- },
- ...VERSION_PROPS,
- found: true,
- }
- : {
- _id: 'doesnt-matter',
- _index: 'doesnt-matter',
- found: false,
- };
- }),
- })
- );
+ client.mget.mockResponseOnce({
+ docs: results.map((x) => {
+ const references =
+ x.references?.map(({ type, id }) => ({ type, id, name: 'ref-name' })) ?? [];
+ return x.found
+ ? {
+ _id: 'doesnt-matter',
+ _index: 'doesnt-matter',
+ _source: {
+ namespaces: SPACES,
+ references,
+ },
+ ...VERSION_PROPS,
+ found: true,
+ }
+ : {
+ _id: 'doesnt-matter',
+ _index: 'doesnt-matter',
+ found: false,
+ };
+ }),
+ });
}
/** Asserts that mget is called for the given objects */
diff --git a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts
index e82755e44aa78..a404f2e9475b7 100644
--- a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts
+++ b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts
@@ -207,7 +207,7 @@ async function getObjectsAndReferences({
}
const bulkGetResponse = await client.mget(
{ body: { docs: makeBulkGetDocs(bulkGetObjects) } },
- { ignore: [404] }
+ { ignore: [404], meta: true }
);
// exit early if we can't verify a 404 response is from Elasticsearch
if (
diff --git a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts
index 5403e146509ae..883d7fa241944 100644
--- a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts
+++ b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts
@@ -12,10 +12,7 @@ import {
mockIsNotFoundFromUnsupportedServer,
} from './internal_bulk_resolve.test.mock';
-import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
-import type { ElasticsearchClient } from 'src/core/server/elasticsearch';
import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks';
-
import { LEGACY_URL_ALIAS_TYPE } from '../../object_types';
import { typeRegistryMock } from '../../saved_objects_type_registry.mock';
import { SavedObjectsSerializer } from '../../serialization';
@@ -40,7 +37,7 @@ beforeEach(() => {
});
describe('internalBulkResolve', () => {
- let client: DeeplyMockedKeys;
+ let client: ReturnType;
let serializer: SavedObjectsSerializer;
let incrementCounterInternal: jest.Mock;
@@ -69,52 +66,48 @@ describe('internalBulkResolve', () => {
function mockBulkResults(
...results: Array<{ found: boolean; targetId?: string; disabled?: boolean }>
) {
- client.bulk.mockReturnValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- items: results.map(({ found, targetId, disabled }) => ({
- update: {
- _index: 'doesnt-matter',
- status: 0,
- get: {
- found,
- _source: {
- ...((targetId || disabled) && {
- [LEGACY_URL_ALIAS_TYPE]: { targetId, disabled },
- }),
- },
- ...VERSION_PROPS,
+ client.bulk.mockResponseOnce({
+ items: results.map(({ found, targetId, disabled }) => ({
+ update: {
+ _index: 'doesnt-matter',
+ status: 0,
+ get: {
+ found,
+ _source: {
+ ...((targetId || disabled) && {
+ [LEGACY_URL_ALIAS_TYPE]: { targetId, disabled },
+ }),
},
+ ...VERSION_PROPS,
},
- })),
- errors: false,
- took: 0,
- })
- );
+ },
+ })),
+ errors: false,
+ took: 0,
+ });
}
/** Mocks the elasticsearch client so it returns the expected results for an mget operation*/
function mockMgetResults(...results: Array<{ found: boolean }>) {
- client.mget.mockReturnValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- docs: results.map((x) => {
- return x.found
- ? {
- _id: 'doesnt-matter',
- _index: 'doesnt-matter',
- _source: {
- foo: 'bar',
- },
- ...VERSION_PROPS,
- found: true,
- }
- : {
- _id: 'doesnt-matter',
- _index: 'doesnt-matter',
- found: false,
- };
- }),
- })
- );
+ client.mget.mockResponseOnce({
+ docs: results.map((x) => {
+ return x.found
+ ? {
+ _id: 'doesnt-matter',
+ _index: 'doesnt-matter',
+ _source: {
+ foo: 'bar',
+ },
+ ...VERSION_PROPS,
+ found: true,
+ }
+ : {
+ _id: 'doesnt-matter',
+ _index: 'doesnt-matter',
+ found: false,
+ };
+ }),
+ });
}
/** Asserts that bulk is called for the given aliases */
@@ -158,16 +151,20 @@ describe('internalBulkResolve', () => {
const error = SavedObjectsErrorHelpers.createUnsupportedTypeError(UNSUPPORTED_TYPE);
return { type: UNSUPPORTED_TYPE, id, error };
}
+
function expectNotFoundError(id: string) {
const error = SavedObjectsErrorHelpers.createGenericNotFoundError(OBJ_TYPE, id);
return { type: OBJ_TYPE, id, error };
}
+
function expectExactMatchResult(id: string) {
return { saved_object: `mock-obj-for-${id}`, outcome: 'exactMatch' };
}
+
function expectAliasMatchResult(id: string) {
return { saved_object: `mock-obj-for-${id}`, outcome: 'aliasMatch', alias_target_id: id };
}
+
// eslint-disable-next-line @typescript-eslint/naming-convention
function expectConflictResult(id: string, alias_target_id: string) {
return { saved_object: `mock-obj-for-${id}`, outcome: 'conflict', alias_target_id };
diff --git a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts
index 6c11fa1f245c7..e032e769b0220 100644
--- a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts
+++ b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts
@@ -138,7 +138,7 @@ export async function internalBulkResolve(
const bulkGetResponse = docsToBulkGet.length
? await client.mget(
{ body: { docs: docsToBulkGet } },
- { ignore: [404] }
+ { ignore: [404], meta: true }
)
: undefined;
// exit early if a 404 isn't from elasticsearch
@@ -293,7 +293,7 @@ async function fetchAndUpdateAliases(
require_alias: true,
body: bulkUpdateDocs,
});
- return bulkUpdateResponse.body.items.map((item) => {
+ return bulkUpdateResponse.items.map((item) => {
// Map the bulk update response to the `_source` fields that were returned for each document
return item.update?.get;
});
diff --git a/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.test.ts b/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.test.ts
index 22c57fe3f280f..4e7ce652bf4bf 100644
--- a/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.test.ts
+++ b/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.test.ts
@@ -54,9 +54,7 @@ describe('deleteLegacyUrlAliases', () => {
body: { error: { type: 'es_type', reason: 'es_reason' } },
})
);
- params.client.updateByQuery.mockResolvedValueOnce(
- elasticsearchClientMock.createErrorTransportRequestPromise(esError)
- );
+ params.client.updateByQuery.mockResolvedValueOnce(Promise.reject(esError));
mockGetEsErrorMessage.mockClear();
mockGetEsErrorMessage.mockReturnValue('Oh no!');
diff --git a/src/core/server/saved_objects/service/lib/preflight_check_for_create.ts b/src/core/server/saved_objects/service/lib/preflight_check_for_create.ts
index 6a7e1294744ac..036a0e417386b 100644
--- a/src/core/server/saved_objects/service/lib/preflight_check_for_create.ts
+++ b/src/core/server/saved_objects/service/lib/preflight_check_for_create.ts
@@ -273,7 +273,7 @@ async function bulkGetObjectsAndAliases(
const bulkGetResponse = docsToBulkGet.length
? await client.mget(
{ body: { docs: docsToBulkGet } },
- { ignore: [404] }
+ { ignore: [404], meta: true }
)
: undefined;
diff --git a/src/core/server/saved_objects/service/lib/repository.test.ts b/src/core/server/saved_objects/service/lib/repository.test.ts
index 41a284764b0ea..1df3ef351c6ae 100644
--- a/src/core/server/saved_objects/service/lib/repository.test.ts
+++ b/src/core/server/saved_objects/service/lib/repository.test.ts
@@ -473,9 +473,7 @@ describe('SavedObjectsRepository', () => {
options?: SavedObjectsCreateOptions
) => {
const response = getMockBulkCreateResponse(objects, options?.namespace);
- client.bulk.mockResolvedValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ client.bulk.mockResponse(response);
return await savedObjectsRepository.bulkCreate(objects, options);
};
@@ -838,9 +836,7 @@ describe('SavedObjectsRepository', () => {
} else {
response = getMockBulkCreateResponse([obj1, obj2]);
}
- client.bulk.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ client.bulk.mockResponseOnce(response);
const objects = [obj1, obj, obj2];
const result = await savedObjectsRepository.bulkCreate(objects);
@@ -941,9 +937,7 @@ describe('SavedObjectsRepository', () => {
},
]);
const bulkResponse = getMockBulkCreateResponse([o1, o5]);
- client.bulk.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(bulkResponse)
- );
+ client.bulk.mockResponseOnce(bulkResponse);
const options = { overwrite: true };
const result = await savedObjectsRepository.bulkCreate(objects, options);
@@ -984,9 +978,7 @@ describe('SavedObjectsRepository', () => {
it(`returns errors for any bulk objects with invalid schemas`, async () => {
const response = getMockBulkCreateResponse([obj3]);
- client.bulk.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ client.bulk.mockResponseOnce(response);
const result = await savedObjectsRepository.bulkCreate([
obj3,
@@ -1089,9 +1081,7 @@ describe('SavedObjectsRepository', () => {
};
const objects = [obj1, obj, obj2];
const response = getMockBulkCreateResponse([obj1, obj2]);
- client.bulk.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ client.bulk.mockResponseOnce(response);
const result = await savedObjectsRepository.bulkCreate(objects);
expect(client.bulk).toHaveBeenCalledTimes(1);
expect(result).toEqual({
@@ -1107,9 +1097,7 @@ describe('SavedObjectsRepository', () => {
// of the document when it actually does not, forcing to cast to any as BulkResponse
// does not contains _source
const response = getMockBulkCreateResponse([obj1, obj2], namespace) as any;
- client.bulk.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ client.bulk.mockResponseOnce(response);
// Bulk create one object with id unspecified, and one with id specified
const result = await savedObjectsRepository.bulkCreate([{ ...obj1, id: undefined }, obj2], {
@@ -1182,9 +1170,7 @@ describe('SavedObjectsRepository', () => {
);
const bulkGetSuccess = async (objects: SavedObject[], options?: SavedObjectsBaseOptions) => {
const response = getMockMgetResponse(objects, options?.namespace);
- client.mget.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ client.mget.mockResponseOnce(response);
const result = await bulkGet(objects, options);
expect(client.mget).toHaveBeenCalledTimes(1);
return result;
@@ -1551,14 +1537,10 @@ describe('SavedObjectsRepository', () => {
const multiNamespaceObjects = objects.filter(({ type }) => registry.isMultiNamespace(type));
if (multiNamespaceObjects?.length) {
const response = getMockMgetResponse(multiNamespaceObjects, options?.namespace);
- client.mget.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ client.mget.mockResponseOnce(response);
}
const response = getMockBulkUpdateResponse(objects, options, includeOriginId);
- client.bulk.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ client.bulk.mockResponseOnce(response);
const result = await savedObjectsRepository.bulkUpdate(objects, options);
expect(client.mget).toHaveBeenCalledTimes(multiNamespaceObjects?.length ? 1 : 0);
return result;
@@ -1825,9 +1807,7 @@ describe('SavedObjectsRepository', () => {
mockGetBulkOperationError.mockReturnValueOnce(undefined);
mockGetBulkOperationError.mockReturnValueOnce(expectedErrorResult.error as Payload);
}
- client.bulk.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(mockResponse)
- );
+ client.bulk.mockResponseOnce(mockResponse);
const result = await savedObjectsRepository.bulkUpdate(objects);
expect(client.bulk).toHaveBeenCalled();
@@ -1848,16 +1828,10 @@ describe('SavedObjectsRepository', () => {
mgetResponse: estypes.MgetResponse,
mgetOptions?: { statusCode?: number }
) => {
- client.mget.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(mgetResponse, {
- statusCode: mgetOptions?.statusCode,
- })
- );
+ client.mget.mockResponseOnce(mgetResponse, { statusCode: mgetOptions?.statusCode });
const bulkResponse = getMockBulkUpdateResponse([obj1, obj2], { namespace });
- client.bulk.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(bulkResponse)
- );
+ client.bulk.mockResponseOnce(bulkResponse);
const result = await savedObjectsRepository.bulkUpdate([obj1, _obj, obj2], options);
expect(client.bulk).toHaveBeenCalled();
@@ -1966,9 +1940,7 @@ describe('SavedObjectsRepository', () => {
};
const objects = [obj1, obj, obj2];
const mockResponse = getMockBulkUpdateResponse(objects);
- client.bulk.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(mockResponse)
- );
+ client.bulk.mockResponseOnce(mockResponse);
const result = await savedObjectsRepository.bulkUpdate(objects);
expect(client.bulk).toHaveBeenCalledTimes(1);
@@ -2150,12 +2122,14 @@ describe('SavedObjectsRepository', () => {
mockPreflightCheckForCreate.mockImplementation(({ objects }) => {
return Promise.resolve(objects.map(({ type, id }) => ({ type, id }))); // respond with no errors by default
});
- client.create.mockImplementation((params) =>
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- _id: params.id,
- ...mockVersionProps,
- } as estypes.CreateResponse)
- );
+ client.create.mockResponseImplementation((params) => {
+ return {
+ body: {
+ _id: params.id,
+ ...mockVersionProps,
+ } as estypes.CreateResponse,
+ };
+ });
});
const type = 'index-pattern';
@@ -2721,15 +2695,11 @@ describe('SavedObjectsRepository', () => {
if (registry.isMultiNamespace(type)) {
const mockGetResponse =
mockGetResponseValue ?? getMockGetResponse({ type, id }, options?.namespace);
- client.get.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(mockGetResponse)
- );
+ client.get.mockResponseOnce(mockGetResponse);
}
- client.delete.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- result: 'deleted',
- } as estypes.DeleteResponse)
- );
+ client.delete.mockResponseOnce({
+ result: 'deleted',
+ } as estypes.DeleteResponse);
const result = await savedObjectsRepository.delete(type, id, options);
expect(client.get).toHaveBeenCalledTimes(registry.isMultiNamespace(type) ? 1 : 0);
return result;
@@ -3023,9 +2993,7 @@ describe('SavedObjectsRepository', () => {
namespace: string,
options?: SavedObjectsDeleteByNamespaceOptions
) => {
- client.updateByQuery.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(mockUpdateResults)
- );
+ client.updateByQuery.mockResponseOnce(mockUpdateResults);
const result = await savedObjectsRepository.deleteByNamespace(namespace, options);
expect(mockGetSearchDsl).toHaveBeenCalledTimes(1);
expect(client.updateByQuery).toHaveBeenCalledTimes(1);
@@ -3097,11 +3065,9 @@ describe('SavedObjectsRepository', () => {
const updatedCount = 42;
const removeReferencesToSuccess = async (options = defaultOptions) => {
- client.updateByQuery.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- updated: updatedCount,
- })
- );
+ client.updateByQuery.mockResponseOnce({
+ updated: updatedCount,
+ });
return await savedObjectsRepository.removeReferencesTo(type, id, options);
};
@@ -3226,15 +3192,13 @@ describe('SavedObjectsRepository', () => {
describe('errors', () => {
it(`throws when ES returns failures`, async () => {
- client.updateByQuery.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- updated: 7,
- failures: [
- { id: 'failure' } as estypes.BulkIndexByScrollFailure,
- { id: 'another-failure' } as estypes.BulkIndexByScrollFailure,
- ],
- })
- );
+ client.updateByQuery.mockResponseOnce({
+ updated: 7,
+ failures: [
+ { id: 'failure' } as estypes.BulkIndexByScrollFailure,
+ { id: 'another-failure' } as estypes.BulkIndexByScrollFailure,
+ ],
+ });
await expect(
savedObjectsRepository.removeReferencesTo(type, id, defaultOptions)
@@ -3322,11 +3286,7 @@ describe('SavedObjectsRepository', () => {
const namespace = 'foo-namespace';
const findSuccess = async (options: SavedObjectsFindOptions, namespace?: string) => {
- client.search.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- generateSearchResults(namespace)
- )
- );
+ client.search.mockResponseOnce(generateSearchResults(namespace));
const result = await savedObjectsRepository.find(options);
expect(mockGetSearchDsl).toHaveBeenCalledTimes(1);
expect(client.search).toHaveBeenCalledTimes(1);
@@ -3818,9 +3778,7 @@ describe('SavedObjectsRepository', () => {
},
options?.namespace
);
- client.get.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ client.get.mockResponseOnce(response);
const result = await savedObjectsRepository.get(type, id, options);
expect(client.get).toHaveBeenCalledTimes(1);
return result;
@@ -4034,31 +3992,32 @@ describe('SavedObjectsRepository', () => {
if (isMultiNamespace) {
const response =
mockGetResponseValue ?? getMockGetResponse({ type, id }, options?.namespace);
- client.get.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ client.get.mockResponseOnce(response);
}
- client.update.mockImplementation((params) =>
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- _id: params.id,
- ...mockVersionProps,
- _index: '.kibana',
- get: {
- found: true,
- _source: {
- type,
- ...mockTimestampFields,
- [type]: {
- ...fields.reduce((acc, field) => {
- acc[typeof field === 'string' ? field : field.fieldName] = 8468;
- return acc;
- }, {} as Record),
- defaultIndex: 'logstash-*',
+
+ client.update.mockResponseImplementation((params) => {
+ return {
+ body: {
+ _id: params.id,
+ ...mockVersionProps,
+ _index: '.kibana',
+ get: {
+ found: true,
+ _source: {
+ type,
+ ...mockTimestampFields,
+ [type]: {
+ ...fields.reduce((acc, field) => {
+ acc[typeof field === 'string' ? field : field.fieldName] = 8468;
+ return acc;
+ }, {} as Record),
+ defaultIndex: 'logstash-*',
+ },
},
},
- },
- } as estypes.UpdateResponse)
- );
+ } as estypes.UpdateResponse,
+ };
+ });
const result = await savedObjectsRepository.incrementCounter(type, id, fields, options);
expect(client.get).toHaveBeenCalledTimes(isMultiNamespace ? 1 : 0);
@@ -4347,26 +4306,28 @@ describe('SavedObjectsRepository', () => {
describe('returns', () => {
it(`formats the ES response`, async () => {
- client.update.mockImplementation((params) =>
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- _id: params.id,
- ...mockVersionProps,
- _index: '.kibana',
- get: {
- found: true,
- _source: {
- type: 'config',
- ...mockTimestampFields,
- config: {
- buildNum: 8468,
- apiCallsCount: 100,
- defaultIndex: 'logstash-*',
+ client.update.mockResponseImplementation((params) => {
+ return {
+ body: {
+ _id: params.id,
+ ...mockVersionProps,
+ _index: '.kibana',
+ get: {
+ found: true,
+ _source: {
+ type: 'config',
+ ...mockTimestampFields,
+ config: {
+ buildNum: 8468,
+ apiCallsCount: 100,
+ defaultIndex: 'logstash-*',
+ },
+ originId,
},
- originId,
},
- },
- } as estypes.UpdateResponse)
- );
+ } as estypes.UpdateResponse,
+ };
+ });
const response = await savedObjectsRepository.incrementCounter(
'config',
@@ -4452,26 +4413,24 @@ describe('SavedObjectsRepository', () => {
options?: SavedObjectsUpdateOptions,
includeOriginId?: boolean
) => {
- client.update.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- {
- _id: `${type}:${id}`,
- ...mockVersionProps,
- result: 'updated',
- // don't need the rest of the source for test purposes, just the namespace and namespaces attributes
- get: {
- _source: {
- namespaces: [options?.namespace ?? 'default'],
- namespace: options?.namespace,
+ client.update.mockResponseOnce(
+ {
+ _id: `${type}:${id}`,
+ ...mockVersionProps,
+ result: 'updated',
+ // don't need the rest of the source for test purposes, just the namespace and namespaces attributes
+ get: {
+ _source: {
+ namespaces: [options?.namespace ?? 'default'],
+ namespace: options?.namespace,
- // "includeOriginId" is not an option for the operation; however, if the existing saved object contains an originId attribute, the
- // operation will return it in the result. This flag is just used for test purposes to modify the mock cluster call response.
- ...(includeOriginId && { originId }),
- },
+ // "includeOriginId" is not an option for the operation; however, if the existing saved object contains an originId attribute, the
+ // operation will return it in the result. This flag is just used for test purposes to modify the mock cluster call response.
+ ...(includeOriginId && { originId }),
},
- } as estypes.UpdateResponse,
- { statusCode: 200 }
- )
+ },
+ } as estypes.UpdateResponse,
+ { statusCode: 200 }
);
};
@@ -4489,12 +4448,7 @@ describe('SavedObjectsRepository', () => {
if (registry.isMultiNamespace(type)) {
const mockGetResponse =
mockGetResponseValue ?? getMockGetResponse({ type, id }, options?.namespace);
- client.get.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { ...mockGetResponse },
- { statusCode: 200 }
- )
- );
+ client.get.mockResponseOnce(mockGetResponse, { statusCode: 200 });
}
mockUpdateResponse(type, id, options, includeOriginId);
const result = await savedObjectsRepository.update(type, id, attributes, options);
@@ -4896,9 +4850,7 @@ describe('SavedObjectsRepository', () => {
const generateResults = (id?: string) => ({ id: id || 'id' });
const successResponse = async (type: string, options?: SavedObjectsOpenPointInTimeOptions) => {
- client.openPointInTime.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(generateResults())
- );
+ client.openPointInTime.mockResponseOnce(generateResults());
const result = await savedObjectsRepository.openPointInTimeForType(type, options);
expect(client.openPointInTime).toHaveBeenCalledTimes(1);
return result;
@@ -4987,9 +4939,7 @@ describe('SavedObjectsRepository', () => {
describe('#closePointInTime', () => {
const generateResults = () => ({ succeeded: true, num_freed: 3 });
const successResponse = async (id: string) => {
- client.closePointInTime.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(generateResults())
- );
+ client.closePointInTime.mockResponseOnce(generateResults());
const result = await savedObjectsRepository.closePointInTime(id);
expect(client.closePointInTime).toHaveBeenCalledTimes(1);
return result;
@@ -5017,9 +4967,7 @@ describe('SavedObjectsRepository', () => {
describe('returns', () => {
it(`returns response body from ES`, async () => {
const results = generateResults();
- client.closePointInTime.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(results)
- );
+ client.closePointInTime.mockResponseOnce(results);
const response = await savedObjectsRepository.closePointInTime('abc123');
expect(response).toEqual(results);
});
diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts
index a8ad0f68dba8b..abfea6e7ebafc 100644
--- a/src/core/server/saved_objects/service/lib/repository.ts
+++ b/src/core/server/saved_objects/service/lib/repository.ts
@@ -392,8 +392,8 @@ export class SavedObjectsRepository {
const { body, statusCode, headers } =
id && overwrite
- ? await this.client.index(requestParams)
- : await this.client.create(requestParams);
+ ? await this.client.index(requestParams, { meta: true })
+ : await this.client.create(requestParams, { meta: true });
// throw if we can't verify a 404 response is from Elasticsearch
if (isNotFoundFromUnsupportedServer({ statusCode, headers })) {
@@ -602,7 +602,7 @@ export class SavedObjectsRepository {
}
const { requestedId, rawMigratedDoc, esRequestIndex } = expectedResult.value;
- const rawResponse = Object.values(bulkResponse?.body.items[esRequestIndex] ?? {})[0] as any;
+ const rawResponse = Object.values(bulkResponse?.items[esRequestIndex] ?? {})[0] as any;
const error = getBulkOperationError(rawMigratedDoc._source.type, requestedId, rawResponse);
if (error) {
@@ -672,7 +672,7 @@ export class SavedObjectsRepository {
docs: bulkGetDocs,
},
},
- { ignore: [404] }
+ { ignore: [404], meta: true }
)
: undefined;
// throw if we can't verify a 404 response is from Elasticsearch
@@ -764,7 +764,7 @@ export class SavedObjectsRepository {
...getExpectedVersionProperties(undefined, preflightResult?.rawDocSource),
refresh,
},
- { ignore: [404] }
+ { ignore: [404], meta: true }
);
if (isNotFoundFromUnsupportedServer({ statusCode, headers })) {
@@ -865,7 +865,7 @@ export class SavedObjectsRepository {
}),
},
},
- { ignore: [404] }
+ { ignore: [404], meta: true }
);
// throw if we can't verify a 404 response is from Elasticsearch
if (isNotFoundFromUnsupportedServer({ statusCode, headers })) {
@@ -1019,6 +1019,7 @@ export class SavedObjectsRepository {
esOptions,
{
ignore: [404],
+ meta: true,
}
);
if (statusCode === 404) {
@@ -1128,7 +1129,7 @@ export class SavedObjectsRepository {
docs: bulkGetDocs,
},
},
- { ignore: [404] }
+ { ignore: [404], meta: true }
)
: undefined;
// fail fast if we can't verify a 404 is from Elasticsearch
@@ -1237,7 +1238,7 @@ export class SavedObjectsRepository {
id: this._serializer.generateRawId(namespace, type, id),
index: this.getIndexForType(type),
},
- { ignore: [404] }
+ { ignore: [404], meta: true }
);
const indexNotFound = statusCode === 404;
// check if we have the elasticsearch header when index is not found and, if we do, ensure it is from Elasticsearch
@@ -1368,8 +1369,8 @@ export class SavedObjectsRepository {
...(Array.isArray(references) && { references }),
};
- const { body } = await this.client
- .update({
+ const body = await this.client
+ .update({
id: this._serializer.generateRawId(namespace, type, id),
index: this.getIndexForType(type),
...getExpectedVersionProperties(version, preflightResult?.rawDocSource),
@@ -1556,6 +1557,7 @@ export class SavedObjectsRepository {
},
{
ignore: [404],
+ meta: true,
}
)
: undefined;
@@ -1655,7 +1657,7 @@ export class SavedObjectsRepository {
}
const { type, id, namespaces, documentToSave, esRequestIndex } = expectedResult.value;
- const response = bulkUpdateResponse?.body.items[esRequestIndex] ?? {};
+ const response = bulkUpdateResponse?.items[esRequestIndex] ?? {};
const rawResponse = Object.values(response)[0] as any;
const error = getBulkOperationError(type, id, rawResponse);
@@ -1734,7 +1736,7 @@ export class SavedObjectsRepository {
}),
},
},
- { ignore: [404] }
+ { ignore: [404], meta: true }
);
// fail fast if we can't verify a 404 is from Elasticsearch
if (isNotFoundFromUnsupportedServer({ statusCode, headers })) {
@@ -1923,7 +1925,7 @@ export class SavedObjectsRepository {
const raw = this._serializer.savedObjectToRaw(migrated as SavedObjectSanitizedDoc);
- const { body } = await this.client.update({
+ const body = await this.client.update({
id: raw._id,
index: this.getIndexForType(type),
refresh,
@@ -2028,6 +2030,7 @@ export class SavedObjectsRepository {
const { body, statusCode, headers } = await this.client.openPointInTime(esOptions, {
ignore: [404],
+ meta: true,
});
if (statusCode === 404) {
@@ -2088,11 +2091,9 @@ export class SavedObjectsRepository {
id: string,
options?: SavedObjectsClosePointInTimeOptions
): Promise {
- const { body } = await this.client.closePointInTime({
+ return await this.client.closePointInTime({
body: { id },
});
-
- return body;
}
/**
@@ -2213,6 +2214,7 @@ export class SavedObjectsRepository {
},
{
ignore: [404],
+ meta: true,
}
);
diff --git a/src/core/server/saved_objects/service/lib/repository_es_client.test.ts b/src/core/server/saved_objects/service/lib/repository_es_client.test.ts
index 97cafec68b905..d06172fc6a673 100644
--- a/src/core/server/saved_objects/service/lib/repository_es_client.test.ts
+++ b/src/core/server/saved_objects/service/lib/repository_es_client.test.ts
@@ -44,7 +44,7 @@ describe('RepositoryEsClient', () => {
it('transform elasticsearch errors into saved objects errors', async () => {
expect.assertions(1);
- client.bulk = jest.fn().mockRejectedValue(new Error('reason'));
+ client.bulk.mockRejectedValue(new Error('reason'));
try {
await repositoryClient.bulk({ body: [] });
} catch (e) {
diff --git a/src/core/server/saved_objects/service/lib/repository_es_client.ts b/src/core/server/saved_objects/service/lib/repository_es_client.ts
index 4c1ae294cc7db..e9893d4b2d570 100644
--- a/src/core/server/saved_objects/service/lib/repository_es_client.ts
+++ b/src/core/server/saved_objects/service/lib/repository_es_client.ts
@@ -28,7 +28,7 @@ const methods = [
type MethodName = typeof methods[number];
-export type RepositoryEsClient = Pick;
+export type RepositoryEsClient = Pick;
export function createRepositoryEsClient(client: ElasticsearchClient): RepositoryEsClient {
return methods.reduce((acc: RepositoryEsClient, key: MethodName) => {
diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts
index 5163c4a4990ad..38bdba0208b8d 100644
--- a/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts
+++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts
@@ -13,8 +13,6 @@ import {
mockDeleteLegacyUrlAliases,
} from './update_objects_spaces.test.mock';
-import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
-import type { ElasticsearchClient } from 'src/core/server/elasticsearch';
import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks';
import { loggerMock } from '../../../logging/logger.mock';
@@ -66,7 +64,7 @@ afterAll(() => {
});
describe('#updateObjectsSpaces', () => {
- let client: DeeplyMockedKeys;
+ let client: ReturnType;
/** Sets up the type registry, saved objects client, etc. and return the full parameters object to be passed to `updateObjectsSpaces` */
function setup({ objects = [], spacesToAdd = [], spacesToRemove = [], options }: SetupParams) {
@@ -93,8 +91,29 @@ describe('#updateObjectsSpaces', () => {
/** Mocks the saved objects client so it returns the expected results */
function mockMgetResults(...results: Array<{ found: boolean }>) {
- client.mget.mockReturnValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ client.mget.mockResponseOnce({
+ docs: results.map((x) =>
+ x.found
+ ? {
+ _id: 'doesnt-matter',
+ _index: 'doesnt-matter',
+ _source: { namespaces: [EXISTING_SPACE] },
+ ...VERSION_PROPS,
+ found: true,
+ }
+ : {
+ _id: 'doesnt-matter',
+ _index: 'doesnt-matter',
+ found: false,
+ }
+ ),
+ });
+ }
+
+ /** Mocks the saved objects client so as to test unsupported server responding with 404 */
+ function mockMgetResultsNotFound(...results: Array<{ found: boolean }>) {
+ client.mget.mockResponseOnce(
+ {
docs: results.map((x) =>
x.found
? {
@@ -110,33 +129,8 @@ describe('#updateObjectsSpaces', () => {
found: false,
}
),
- })
- );
- }
- /** Mocks the saved objects client so as to test unsupported server responding with 404 */
- function mockMgetResultsNotFound(...results: Array<{ found: boolean }>) {
- client.mget.mockReturnValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- {
- docs: results.map((x) =>
- x.found
- ? {
- _id: 'doesnt-matter',
- _index: 'doesnt-matter',
- _source: { namespaces: [EXISTING_SPACE] },
- ...VERSION_PROPS,
- found: true,
- }
- : {
- _id: 'doesnt-matter',
- _index: 'doesnt-matter',
- found: false,
- }
- ),
- },
- { statusCode: 404 },
- {}
- )
+ },
+ { statusCode: 404, headers: {} }
);
}
@@ -155,13 +149,11 @@ describe('#updateObjectsSpaces', () => {
mockGetBulkOperationError.mockReturnValueOnce(undefined);
}
});
- client.bulk.mockReturnValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- items: results.map(() => ({})), // as long as the result does not contain an error field, it is treated as a success
- errors: false,
- took: 0,
- })
- );
+ client.bulk.mockResponseOnce({
+ items: results.map(() => ({})), // as long as the result does not contain an error field, it is treated as a success
+ errors: false,
+ took: 0,
+ });
}
/** Asserts that mget is called for the given objects */
diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts
index f3c97382c3747..26da4909df247 100644
--- a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts
+++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts
@@ -124,6 +124,7 @@ const MAX_CONCURRENT_ALIAS_DELETIONS = 10;
function isMgetError(doc?: estypes.MgetResponseItem): doc is estypes.MgetMultiGetError {
return Boolean(doc && 'error' in doc);
}
+
/**
* Gets all references and transitive references of the given objects. Ignores any object and/or reference that is not a multi-namespace
* type.
@@ -204,7 +205,7 @@ export async function updateObjectsSpaces({
const bulkGetResponse = bulkGetDocs.length
? await client.mget(
{ body: { docs: bulkGetDocs } },
- { ignore: [404] }
+ { ignore: [404], meta: true }
)
: undefined;
// fail fast if we can't verify a 404 response is from Elasticsearch
@@ -338,7 +339,7 @@ export async function updateObjectsSpaces({
const { type, id, updatedSpaces, esRequestIndex } = expectedResult.value;
if (esRequestIndex !== undefined) {
- const response = bulkOperationResponse?.body.items[esRequestIndex] ?? {};
+ const response = bulkOperationResponse?.items[esRequestIndex] ?? {};
const rawResponse = Object.values(response)[0] as any;
const error = getBulkOperationError(type, id, rawResponse);
if (error) {
diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md
index a722e6eb98b02..111f2ed0001fc 100644
--- a/src/core/server/server.api.md
+++ b/src/core/server/server.api.md
@@ -10,6 +10,7 @@ import { AddConfigDeprecation } from '@kbn/config';
import Boom from '@hapi/boom';
import { ByteSizeValue } from '@kbn/config-schema';
import { CliArgs } from '@kbn/config';
+import type { Client } from '@elastic/elasticsearch';
import type { ClientOptions } from '@elastic/elasticsearch/lib/client';
import { ConditionalType } from '@kbn/config-schema';
import { ConfigDeprecation } from '@kbn/config';
@@ -31,7 +32,6 @@ import { EnvironmentMode } from '@kbn/config';
import { errors } from '@elastic/elasticsearch';
import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IncomingHttpHeaders } from 'http';
-import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import { Logger } from '@kbn/logging';
import { LoggerFactory } from '@kbn/logging';
import { LogLevel as LogLevel_2 } from '@kbn/logging';
@@ -53,9 +53,6 @@ import { ResponseToolkit } from '@hapi/hapi';
import { SchemaTypeError } from '@kbn/config-schema';
import { ShallowPromise } from '@kbn/utility-types';
import { Stream } from 'stream';
-import type { TransportRequestOptions } from '@elastic/elasticsearch';
-import type { TransportRequestParams } from '@elastic/elasticsearch';
-import type { TransportResult } from '@elastic/elasticsearch';
import { Type } from '@kbn/config-schema';
import { TypeOf } from '@kbn/config-schema';
import { UiCounterMetricType } from '@kbn/analytics';
@@ -888,11 +885,7 @@ export { EcsEventOutcome }
export { EcsEventType }
// @public
-export type ElasticsearchClient = Omit & {
- transport: {
- request(params: TransportRequestParams, options?: TransportRequestOptions): Promise>;
- };
-};
+export type ElasticsearchClient = Omit;
// @public
export type ElasticsearchClientConfig = Pick & {
@@ -3167,7 +3160,7 @@ export const validBodyOutput: readonly ["data", "stream"];
// Warnings were encountered during analysis:
//
-// src/core/server/elasticsearch/client/types.ts:93:7 - (ae-forgotten-export) The symbol "Explanation" needs to be exported by the entry point index.d.ts
+// src/core/server/elasticsearch/client/types.ts:81:7 - (ae-forgotten-export) The symbol "Explanation" needs to be exported by the entry point index.d.ts
// src/core/server/http/router/response.ts:302:3 - (ae-forgotten-export) The symbol "KibanaResponse" needs to be exported by the entry point index.d.ts
// src/core/server/plugins/types.ts:375:3 - (ae-forgotten-export) The symbol "SharedGlobalConfigKeys" needs to be exported by the entry point index.d.ts
// src/core/server/plugins/types.ts:377:3 - (ae-forgotten-export) The symbol "SavedObjectsConfigType" needs to be exported by the entry point index.d.ts
diff --git a/src/core/server/ui_settings/integration_tests/lib/servers.ts b/src/core/server/ui_settings/integration_tests/lib/servers.ts
index d94ab98060a27..2591e4050341c 100644
--- a/src/core/server/ui_settings/integration_tests/lib/servers.ts
+++ b/src/core/server/ui_settings/integration_tests/lib/servers.ts
@@ -8,7 +8,7 @@
import type supertest from 'supertest';
import type { SavedObjectsClientContract, IUiSettingsClient } from 'src/core/server';
-import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import {
createTestServers,
@@ -26,7 +26,7 @@ let kbn: TestKibanaUtils;
interface AllServices {
savedObjectsClient: SavedObjectsClientContract;
- esClient: KibanaClient;
+ esClient: Client;
uiSettings: IUiSettingsClient;
supertest: (method: HttpMethod, path: string) => supertest.Test;
}
@@ -55,7 +55,7 @@ export function getServices() {
return services;
}
- const esClient = esServer.es.getKibanaEsClient();
+ const esClient = esServer.es.getClient();
const savedObjectsClient = kbn.coreStart.savedObjects.getScopedClient(
httpServerMock.createKibanaRequest()
diff --git a/src/plugins/data/server/autocomplete/terms_agg.test.ts b/src/plugins/data/server/autocomplete/terms_agg.test.ts
index eb24b71cae274..f9d45475d9e2f 100644
--- a/src/plugins/data/server/autocomplete/terms_agg.test.ts
+++ b/src/plugins/data/server/autocomplete/terms_agg.test.ts
@@ -10,7 +10,6 @@ import { coreMock } from '../../../../core/server/mocks';
import { ElasticsearchClient, SavedObjectsClientContract } from 'kibana/server';
import { ConfigSchema } from '../../config';
import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
-import type { TransportResult } from '@elastic/elasticsearch';
import { termsAggSuggestions } from './terms_agg';
import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { duration } from 'moment';
@@ -25,14 +24,12 @@ const configMock = {
// @ts-expect-error not full interface
const mockResponse = {
- body: {
- aggregations: {
- suggestions: {
- buckets: [{ key: 'whoa' }, { key: 'amazing' }],
- },
+ aggregations: {
+ suggestions: {
+ buckets: [{ key: 'whoa' }, { key: 'amazing' }],
},
},
-} as TransportResult>;
+} as estypes.SearchResponse;
jest.mock('../data_views');
diff --git a/src/plugins/data/server/autocomplete/terms_agg.ts b/src/plugins/data/server/autocomplete/terms_agg.ts
index 20a8a5c212f26..742812adafbb9 100644
--- a/src/plugins/data/server/autocomplete/terms_agg.ts
+++ b/src/plugins/data/server/autocomplete/terms_agg.ts
@@ -45,8 +45,8 @@ export async function termsAggSuggestions(
);
const buckets =
- get(result.body, 'aggregations.suggestions.buckets') ||
- get(result.body, 'aggregations.nestedSuggestions.suggestions.buckets');
+ get(result, 'aggregations.suggestions.buckets') ||
+ get(result, 'aggregations.nestedSuggestions.suggestions.buckets');
return map(buckets ?? [], 'key');
}
diff --git a/src/plugins/data/server/autocomplete/terms_enum.test.ts b/src/plugins/data/server/autocomplete/terms_enum.test.ts
index c0750ead5cc0a..ce2741f612ba8 100644
--- a/src/plugins/data/server/autocomplete/terms_enum.test.ts
+++ b/src/plugins/data/server/autocomplete/terms_enum.test.ts
@@ -11,7 +11,6 @@ import { coreMock } from '../../../../core/server/mocks';
import { ElasticsearchClient, SavedObjectsClientContract } from 'kibana/server';
import { ConfigSchema } from '../../config';
import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
-import type { TransportResult } from '@elastic/elasticsearch';
import { TermsEnumResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
let savedObjectsClientMock: jest.Mocked;
@@ -19,9 +18,7 @@ let esClientMock: DeeplyMockedKeys;
const configMock = {
autocomplete: { valueSuggestions: { tiers: ['data_hot', 'data_warm', 'data_content'] } },
} as ConfigSchema;
-const mockResponse = {
- body: { terms: ['whoa', 'amazing'] },
-};
+const mockResponse = { terms: ['whoa', 'amazing'] };
jest.mock('../data_views');
@@ -30,9 +27,7 @@ describe('_terms_enum suggestions', () => {
const requestHandlerContext = coreMock.createRequestHandlerContext();
savedObjectsClientMock = requestHandlerContext.savedObjects.client;
esClientMock = requestHandlerContext.elasticsearch.client.asCurrentUser;
- esClientMock.termsEnum.mockResolvedValue(
- mockResponse as unknown as TransportResult
- );
+ esClientMock.termsEnum.mockResolvedValue(mockResponse as unknown as TermsEnumResponse);
});
it('calls the _terms_enum API with the field, query, filters, and config tiers', async () => {
@@ -73,7 +68,7 @@ describe('_terms_enum suggestions', () => {
"index": "index",
}
`);
- expect(result).toEqual(mockResponse.body.terms);
+ expect(result).toEqual(mockResponse.terms);
});
it('calls the _terms_enum API and fallback to fieldName when field is null', async () => {
@@ -113,6 +108,6 @@ describe('_terms_enum suggestions', () => {
"index": "index",
}
`);
- expect(result).toEqual(mockResponse.body.terms);
+ expect(result).toEqual(mockResponse.terms);
});
});
diff --git a/src/plugins/data/server/autocomplete/terms_enum.ts b/src/plugins/data/server/autocomplete/terms_enum.ts
index 201ff32c056ce..e4dca0a739087 100644
--- a/src/plugins/data/server/autocomplete/terms_enum.ts
+++ b/src/plugins/data/server/autocomplete/terms_enum.ts
@@ -54,5 +54,5 @@ export async function termsEnumSuggestions(
}
);
- return result.body.terms;
+ return result.terms;
}
diff --git a/src/plugins/data/server/kql_telemetry/usage_collector/fetch.test.ts b/src/plugins/data/server/kql_telemetry/usage_collector/fetch.test.ts
index 912526b22151f..fb874e4a41c20 100644
--- a/src/plugins/data/server/kql_telemetry/usage_collector/fetch.test.ts
+++ b/src/plugins/data/server/kql_telemetry/usage_collector/fetch.test.ts
@@ -30,45 +30,41 @@ function setupMockCallCluster(
function mockedEsGetMethod() {
if (optCount === null) {
return Promise.resolve({
- body: {
- _index: '.kibana_1',
- _id: 'kql-telemetry:kql-telemetry',
- found: false,
- },
+ _index: '.kibana_1',
+ _id: 'kql-telemetry:kql-telemetry',
+ found: false,
});
} else {
return Promise.resolve({
- body: {
- _source: {
- 'kql-telemetry': { ...optCount },
- type: 'kql-telemetry',
- updated_at: '2018-10-05T20:20:56.258Z',
- },
+ _source: {
+ 'kql-telemetry': { ...optCount },
+ type: 'kql-telemetry',
+ updated_at: '2018-10-05T20:20:56.258Z',
},
});
}
}
+
function mockedEsSearchMethod() {
if (language === 'missingConfigDoc') {
- return Promise.resolve({ body: { hits: { hits: [] } } });
+ return Promise.resolve({ hits: { hits: [] } });
} else {
return Promise.resolve({
- body: {
- hits: {
- hits: [
- {
- _source: {
- config: {
- 'search:queryLanguage': language,
- },
+ hits: {
+ hits: [
+ {
+ _source: {
+ config: {
+ 'search:queryLanguage': language,
},
},
- ],
- },
+ },
+ ],
},
});
}
}
+
const esClientMock = {
get: jest.fn().mockImplementation(mockedEsGetMethod),
search: jest.fn().mockImplementation(mockedEsSearchMethod),
diff --git a/src/plugins/data/server/kql_telemetry/usage_collector/fetch.ts b/src/plugins/data/server/kql_telemetry/usage_collector/fetch.ts
index c04d8a89486af..bad26c1cf8f80 100644
--- a/src/plugins/data/server/kql_telemetry/usage_collector/fetch.ts
+++ b/src/plugins/data/server/kql_telemetry/usage_collector/fetch.ts
@@ -20,7 +20,7 @@ export interface Usage {
export function fetchProvider(index: string) {
return async ({ esClient }: CollectorFetchContext): Promise => {
- const [{ body: response }, { body: config }] = await Promise.all([
+ const [response, config] = await Promise.all([
esClient.get(
{
index,
diff --git a/src/plugins/data/server/search/collectors/fetch.ts b/src/plugins/data/server/search/collectors/fetch.ts
index a2d1917fc4770..054d04d6fbcae 100644
--- a/src/plugins/data/server/search/collectors/fetch.ts
+++ b/src/plugins/data/server/search/collectors/fetch.ts
@@ -15,7 +15,7 @@ interface SearchTelemetry {
export function fetchProvider(kibanaIndex: string) {
return async ({ esClient }: CollectorFetchContext): Promise => {
- const { body: esResponse } = await esClient.search(
+ const esResponse = await esClient.search(
{
index: kibanaIndex,
body: {
diff --git a/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts
index 3d9294765cc15..ebb07cff6e05d 100644
--- a/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts
+++ b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts
@@ -53,11 +53,15 @@ export const eqlSearchStrategyProvider = (
...request.params,
};
const response = id
- ? await client.get({ ...params, id }, { ...request.options, signal: options.abortSignal })
+ ? await client.get(
+ { ...params, id },
+ { ...request.options, signal: options.abortSignal, meta: true }
+ )
: // @ts-expect-error optional key cannot be used since search doesn't expect undefined
await client.search(params as EqlSearchStrategyRequest['params'], {
...request.options,
abortController: { signal: options.abortSignal },
+ meta: true,
});
return toEqlKibanaSearchResponse(response as TransportResult);
diff --git a/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts b/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts
index c06a75f3148a8..de5962763aed4 100644
--- a/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts
+++ b/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts
@@ -5,7 +5,8 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { TransportResult } from '@elastic/elasticsearch';
+
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { elasticsearchServiceMock } from '../../../../../../core/server/mocks';
import { pluginInitializerContextConfigMock } from '../../../../../../core/server/mocks';
import { esSearchStrategyProvider } from './es_search_strategy';
@@ -23,31 +24,28 @@ describe('ES search strategy', () => {
skipped: 2,
successful: 7,
},
- } as const;
- let mockedApiCaller: Promise>;
- let mockApiCaller: jest.Mock<() => TransportResult>;
+ } as estypes.SearchResponse;
+
const mockLogger: any = {
debug: () => {},
};
+ let esClient: ReturnType;
+
function getMockedDeps(err?: Record) {
- mockApiCaller = jest.fn().mockImplementation(() => {
- if (err) {
- mockedApiCaller = elasticsearchServiceMock.createErrorTransportRequestPromise(err);
- } else {
- mockedApiCaller = elasticsearchServiceMock.createSuccessTransportRequestPromise(
- successBody,
- { statusCode: 200 }
- );
- }
- return mockedApiCaller;
- });
+ esClient = elasticsearchServiceMock.createElasticsearchClient();
+
+ if (err) {
+ esClient.search.mockImplementation(() => Promise.reject(err));
+ } else {
+ esClient.search.mockResponse(successBody, { statusCode: 200 });
+ }
return {
uiSettingsClient: {
get: () => {},
},
- esClient: { asCurrentUser: { search: mockApiCaller } },
+ esClient: { asCurrentUser: esClient },
} as unknown as SearchStrategyDependencies;
}
@@ -65,8 +63,8 @@ describe('ES search strategy', () => {
await esSearchStrategyProvider(mockConfig$, mockLogger)
.search({ params }, {}, getMockedDeps())
.subscribe(() => {
- expect(mockApiCaller).toBeCalled();
- expect(mockApiCaller.mock.calls[0][0]).toEqual({
+ expect(esClient.search).toBeCalled();
+ expect(esClient.search.mock.calls[0][0]).toEqual({
...params,
ignore_unavailable: true,
track_total_hits: true,
@@ -81,8 +79,8 @@ describe('ES search strategy', () => {
await esSearchStrategyProvider(mockConfig$, mockLogger)
.search({ params }, {}, getMockedDeps())
.subscribe(() => {
- expect(mockApiCaller).toBeCalled();
- expect(mockApiCaller.mock.calls[0][0]).toEqual({
+ expect(esClient.search).toBeCalled();
+ expect(esClient.search.mock.calls[0][0]).toEqual({
...params,
track_total_hits: true,
});
@@ -117,8 +115,8 @@ describe('ES search strategy', () => {
.search({ params }, { abortSignal: abortController.signal }, getMockedDeps())
.toPromise();
- expect(mockApiCaller).toBeCalled();
- expect(mockApiCaller.mock.calls[0][0]).toEqual({
+ expect(esClient.search).toBeCalled();
+ expect(esClient.search.mock.calls[0][0]).toEqual({
...params,
track_total_hits: true,
});
@@ -139,7 +137,7 @@ describe('ES search strategy', () => {
.search({ params }, {}, getMockedDeps(errResponse))
.toPromise();
} catch (e) {
- expect(mockApiCaller).toBeCalled();
+ expect(esClient.search).toBeCalled();
expect(e).toBeInstanceOf(KbnServerError);
expect(e.statusCode).toBe(404);
expect(e.message).toBe(errResponse.message);
@@ -157,7 +155,7 @@ describe('ES search strategy', () => {
.search({ params }, {}, getMockedDeps(errResponse))
.toPromise();
} catch (e) {
- expect(mockApiCaller).toBeCalled();
+ expect(esClient.search).toBeCalled();
expect(e).toBeInstanceOf(KbnServerError);
expect(e.statusCode).toBe(500);
expect(e.message).toBe(errResponse.message);
@@ -175,7 +173,7 @@ describe('ES search strategy', () => {
.search({ params }, {}, getMockedDeps(errResponse))
.toPromise();
} catch (e) {
- expect(mockApiCaller).toBeCalled();
+ expect(esClient.search).toBeCalled();
expect(e).toBeInstanceOf(KbnServerError);
expect(e.statusCode).toBe(500);
expect(e.message).toBe(errResponse.message);
@@ -192,7 +190,7 @@ describe('ES search strategy', () => {
.search({ indexType: 'banana', params }, {}, getMockedDeps())
.toPromise();
} catch (e) {
- expect(mockApiCaller).not.toBeCalled();
+ expect(esClient.search).not.toBeCalled();
expect(e).toBeInstanceOf(KbnServerError);
expect(e.message).toBe('Unsupported index pattern type banana');
expect(e.statusCode).toBe(400);
diff --git a/src/plugins/data/server/search/strategies/es_search/es_search_strategy.ts b/src/plugins/data/server/search/strategies/es_search/es_search_strategy.ts
index 097e099bf2997..5fd734138824d 100644
--- a/src/plugins/data/server/search/strategies/es_search/es_search_strategy.ts
+++ b/src/plugins/data/server/search/strategies/es_search/es_search_strategy.ts
@@ -46,7 +46,7 @@ export const esSearchStrategyProvider = (
...(terminateAfter ? { terminate_after: terminateAfter } : {}),
...requestParams,
};
- const { body } = await esClient.asCurrentUser.search(params, {
+ const body = await esClient.asCurrentUser.search(params, {
signal: abortSignal,
});
const response = shimHitsTotal(body, options);
diff --git a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts
index e94f1aa44d351..7a9caa4998f9a 100644
--- a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts
+++ b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts
@@ -68,9 +68,13 @@ export const enhancedEsSearchStrategyProvider = (
...request.params,
};
const { body, headers } = id
- ? await client.asyncSearch.get({ ...params, id }, { signal: options.abortSignal })
+ ? await client.asyncSearch.get(
+ { ...params, id },
+ { signal: options.abortSignal, meta: true }
+ )
: await client.asyncSearch.submit(params, {
signal: options.abortSignal,
+ meta: true,
});
const response = shimHitsTotal(body.response, options);
@@ -124,6 +128,7 @@ export const enhancedEsSearchStrategyProvider = (
},
{
signal: options?.abortSignal,
+ meta: true,
}
);
diff --git a/src/plugins/data_view_field_editor/server/routes/field_preview.ts b/src/plugins/data_view_field_editor/server/routes/field_preview.ts
index e95c12469ffb9..022cd92a4bb1e 100644
--- a/src/plugins/data_view_field_editor/server/routes/field_preview.ts
+++ b/src/plugins/data_view_field_editor/server/routes/field_preview.ts
@@ -70,7 +70,7 @@ export const registerFieldPreviewRoute = ({ router }: RouteDependencies): void =
body,
});
- const fieldValue = response.body.hits.hits[0]?.fields?.my_runtime_field ?? '';
+ const fieldValue = response.hits.hits[0]?.fields?.my_runtime_field ?? '';
return res.ok({ body: { values: fieldValue } });
} catch (error: any) {
diff --git a/src/plugins/data_view_management/server/routes/preview_scripted_field.ts b/src/plugins/data_view_management/server/routes/preview_scripted_field.ts
index cc161859f4189..6756761fe9653 100644
--- a/src/plugins/data_view_management/server/routes/preview_scripted_field.ts
+++ b/src/plugins/data_view_management/server/routes/preview_scripted_field.ts
@@ -28,23 +28,27 @@ export function registerPreviewScriptedFieldRoute(router: IRouter): void {
const { index, name, script, query, additionalFields } = request.body;
try {
- const response = await client.search({
- index,
- body: {
- _source: additionalFields && additionalFields.length > 0 ? additionalFields : undefined,
- size: 10,
- timeout: '30s',
- query: query ?? { match_all: {} },
- script_fields: {
- [name]: {
- script: {
- lang: 'painless',
- source: script,
+ const response = await client.search(
+ {
+ index,
+ body: {
+ _source:
+ additionalFields && additionalFields.length > 0 ? additionalFields : undefined,
+ size: 10,
+ timeout: '30s',
+ query: query ?? { match_all: {} },
+ script_fields: {
+ [name]: {
+ script: {
+ lang: 'painless',
+ source: script,
+ },
},
},
},
},
- });
+ { meta: true }
+ );
return res.ok({ body: response });
} catch (err) {
diff --git a/src/plugins/data_view_management/server/routes/resolve_index.ts b/src/plugins/data_view_management/server/routes/resolve_index.ts
index 22c214f2adee2..f668fb1f1b8de 100644
--- a/src/plugins/data_view_management/server/routes/resolve_index.ts
+++ b/src/plugins/data_view_management/server/routes/resolve_index.ts
@@ -31,7 +31,7 @@ export function registerResolveIndexRoute(router: IRouter): void {
},
},
async (context, req, res) => {
- const { body } = await context.core.elasticsearch.client.asCurrentUser.indices.resolveIndex({
+ const body = await context.core.elasticsearch.client.asCurrentUser.indices.resolveIndex({
name: req.params.query,
expand_wildcards: req.query.expand_wildcards || 'open',
});
diff --git a/src/plugins/data_views/server/fetcher/index_patterns_fetcher.test.ts b/src/plugins/data_views/server/fetcher/index_patterns_fetcher.test.ts
index f55609d75a066..8f1749a4b61fa 100644
--- a/src/plugins/data_views/server/fetcher/index_patterns_fetcher.test.ts
+++ b/src/plugins/data_views/server/fetcher/index_patterns_fetcher.test.ts
@@ -5,46 +5,46 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
+
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IndexPatternsFetcher } from '.';
-import { ElasticsearchClient } from 'kibana/server';
+import { elasticsearchServiceMock } from '../../../../core/server/mocks';
import * as indexNotFoundException from './index_not_found_exception.json';
describe('Index Pattern Fetcher - server', () => {
let indexPatterns: IndexPatternsFetcher;
- let esClient: ElasticsearchClient;
+ let esClient: ReturnType;
const emptyResponse = {
- body: {
- indices: [],
- },
+ indices: [],
};
const response = {
- body: {
- indices: ['b'],
- fields: [{ name: 'foo' }, { name: 'bar' }, { name: 'baz' }],
- },
+ indices: ['b'],
+ fields: [{ name: 'foo' }, { name: 'bar' }, { name: 'baz' }],
};
const patternList = ['a', 'b', 'c'];
beforeEach(() => {
jest.clearAllMocks();
- esClient = {
- fieldCaps: jest.fn().mockResolvedValueOnce(emptyResponse).mockResolvedValue(response),
- } as unknown as ElasticsearchClient;
+ esClient = elasticsearchServiceMock.createElasticsearchClient();
indexPatterns = new IndexPatternsFetcher(esClient);
});
it('Removes pattern without matching indices', async () => {
+ esClient.fieldCaps
+ .mockResponseOnce(emptyResponse as unknown as estypes.FieldCapsResponse)
+ .mockResponse(response as unknown as estypes.FieldCapsResponse);
// first field caps request returns empty
const result = await indexPatterns.validatePatternListActive(patternList);
expect(result).toEqual(['b', 'c']);
});
it('Keeps matching and negating patterns', async () => {
+ esClient.fieldCaps
+ .mockResponseOnce(emptyResponse as unknown as estypes.FieldCapsResponse)
+ .mockResponse(response as unknown as estypes.FieldCapsResponse);
// first field caps request returns empty
const result = await indexPatterns.validatePatternListActive(['-a', 'b', 'c']);
expect(result).toEqual(['-a', 'c']);
});
it('Returns all patterns when all match indices', async () => {
- esClient = {
- fieldCaps: jest.fn().mockResolvedValue(response),
- } as unknown as ElasticsearchClient;
+ esClient.fieldCaps.mockResponse(response as unknown as estypes.FieldCapsResponse);
indexPatterns = new IndexPatternsFetcher(esClient);
const result = await indexPatterns.validatePatternListActive(patternList);
expect(result).toEqual(patternList);
@@ -52,6 +52,7 @@ describe('Index Pattern Fetcher - server', () => {
it('Removes pattern when error is thrown', async () => {
class ServerError extends Error {
public body?: Record;
+
constructor(
message: string,
public readonly statusCode: number,
@@ -61,34 +62,29 @@ describe('Index Pattern Fetcher - server', () => {
this.body = errBody;
}
}
- esClient = {
- fieldCaps: jest
- .fn()
- .mockResolvedValueOnce(response)
- .mockRejectedValue(
+
+ esClient.fieldCaps
+ .mockResponseOnce(response as unknown as estypes.FieldCapsResponse)
+ .mockImplementationOnce(() => {
+ return Promise.reject(
new ServerError('index_not_found_exception', 404, indexNotFoundException)
- ),
- } as unknown as ElasticsearchClient;
+ );
+ });
+
indexPatterns = new IndexPatternsFetcher(esClient);
const result = await indexPatterns.validatePatternListActive(patternList);
expect(result).toEqual([patternList[0]]);
});
it('When allowNoIndices is false, run validatePatternListActive', async () => {
- const fieldCapsMock = jest.fn();
- esClient = {
- fieldCaps: fieldCapsMock.mockResolvedValue(response),
- } as unknown as ElasticsearchClient;
+ esClient.fieldCaps.mockResponse(response as unknown as estypes.FieldCapsResponse);
indexPatterns = new IndexPatternsFetcher(esClient);
await indexPatterns.getFieldsForWildcard({ pattern: patternList });
- expect(fieldCapsMock.mock.calls).toHaveLength(4);
+ expect(esClient.fieldCaps).toHaveBeenCalledTimes(4);
});
it('When allowNoIndices is true, do not run validatePatternListActive', async () => {
- const fieldCapsMock = jest.fn();
- esClient = {
- fieldCaps: fieldCapsMock.mockResolvedValue(response),
- } as unknown as ElasticsearchClient;
+ esClient.fieldCaps.mockResponse(response as unknown as estypes.FieldCapsResponse);
indexPatterns = new IndexPatternsFetcher(esClient, true);
await indexPatterns.getFieldsForWildcard({ pattern: patternList });
- expect(fieldCapsMock.mock.calls).toHaveLength(1);
+ expect(esClient.fieldCaps).toHaveBeenCalledTimes(1);
});
});
diff --git a/src/plugins/data_views/server/fetcher/index_patterns_fetcher.ts b/src/plugins/data_views/server/fetcher/index_patterns_fetcher.ts
index 148e497d7ef02..dce48a6d96208 100644
--- a/src/plugins/data_views/server/fetcher/index_patterns_fetcher.ts
+++ b/src/plugins/data_views/server/fetcher/index_patterns_fetcher.ts
@@ -37,10 +37,12 @@ interface FieldSubType {
export class IndexPatternsFetcher {
private elasticsearchClient: ElasticsearchClient;
private allowNoIndices: boolean;
+
constructor(elasticsearchClient: ElasticsearchClient, allowNoIndices: boolean = false) {
this.elasticsearchClient = elasticsearchClient;
this.allowNoIndices = allowNoIndices;
}
+
/**
* Get a list of field objects for an index pattern that may contain wildcards
*
@@ -80,11 +82,9 @@ export class IndexPatternsFetcher {
if (type === 'rollup' && rollupIndex) {
const rollupFields: FieldDescriptor[] = [];
const rollupIndexCapabilities = getCapabilitiesForRollupIndices(
- (
- await this.elasticsearchClient.rollup.getRollupIndexCaps({
- index: rollupIndex,
- })
- ).body
+ await this.elasticsearchClient.rollup.getRollupIndexCaps({
+ index: rollupIndex,
+ })
)[rollupIndex].aggs;
const fieldCapsResponseObj = keyBy(fieldCapsResponse, 'name');
// Keep meta fields
@@ -150,7 +150,7 @@ export class IndexPatternsFetcher {
ignore_unavailable: true,
allow_no_indices: false,
});
- return searchResponse.body.indices.length > 0;
+ return searchResponse.indices.length > 0;
})
.map((p) => p.catch(() => false))
);
diff --git a/src/plugins/data_views/server/fetcher/lib/es_api.ts b/src/plugins/data_views/server/fetcher/lib/es_api.ts
index d01bf58048f66..fe0a8fb126aec 100644
--- a/src/plugins/data_views/server/fetcher/lib/es_api.ts
+++ b/src/plugins/data_views/server/fetcher/lib/es_api.ts
@@ -68,13 +68,16 @@ export async function callFieldCapsApi(params: FieldCapsApiParams) {
},
} = params;
try {
- return await callCluster.fieldCaps({
- index: indices,
- fields: '*',
- ignore_unavailable: true,
- index_filter: filter,
- ...fieldCapsOptions,
- });
+ return await callCluster.fieldCaps(
+ {
+ index: indices,
+ fields: '*',
+ ignore_unavailable: true,
+ index_filter: filter,
+ ...fieldCapsOptions,
+ },
+ { meta: true }
+ );
} catch (error) {
throw convertEsError(indices, error);
}
diff --git a/src/plugins/data_views/server/fetcher/lib/resolve_time_pattern.test.js b/src/plugins/data_views/server/fetcher/lib/resolve_time_pattern.test.js
index 597770dff0a90..e71022bfe6b26 100644
--- a/src/plugins/data_views/server/fetcher/lib/resolve_time_pattern.test.js
+++ b/src/plugins/data_views/server/fetcher/lib/resolve_time_pattern.test.js
@@ -64,15 +64,13 @@ describe('server/index_patterns/service/lib/resolve_time_pattern', () => {
describe('read response', () => {
it('returns all aliases names in result.all, ordered by time desc', async () => {
sandbox.stub(callIndexAliasApiNS, 'callIndexAliasApi').returns({
- body: {
- 'logs-2016.2': {},
- 'logs-Saturday-2017.1': {},
- 'logs-2016.1': {},
- 'logs-Sunday-2017.1': {},
- 'logs-2015': {},
- 'logs-2016.3': {},
- 'logs-Friday-2017.1': {},
- },
+ 'logs-2016.2': {},
+ 'logs-Saturday-2017.1': {},
+ 'logs-2016.1': {},
+ 'logs-Sunday-2017.1': {},
+ 'logs-2015': {},
+ 'logs-2016.3': {},
+ 'logs-Friday-2017.1': {},
});
const resp = await resolveTimePattern(noop, TIME_PATTERN);
@@ -90,15 +88,13 @@ describe('server/index_patterns/service/lib/resolve_time_pattern', () => {
it('returns all indices matching the time pattern in matches, ordered by time desc', async () => {
sandbox.stub(callIndexAliasApiNS, 'callIndexAliasApi').returns({
- body: {
- 'logs-2016.2': {},
- 'logs-Saturday-2017.1': {},
- 'logs-2016.1': {},
- 'logs-Sunday-2017.1': {},
- 'logs-2015': {},
- 'logs-2016.3': {},
- 'logs-Friday-2017.1': {},
- },
+ 'logs-2016.2': {},
+ 'logs-Saturday-2017.1': {},
+ 'logs-2016.1': {},
+ 'logs-Sunday-2017.1': {},
+ 'logs-2015': {},
+ 'logs-2016.3': {},
+ 'logs-Friday-2017.1': {},
});
const resp = await resolveTimePattern(noop, TIME_PATTERN);
diff --git a/src/plugins/data_views/server/fetcher/lib/resolve_time_pattern.ts b/src/plugins/data_views/server/fetcher/lib/resolve_time_pattern.ts
index 32b9d8c7f893f..0d487cae4ef41 100644
--- a/src/plugins/data_views/server/fetcher/lib/resolve_time_pattern.ts
+++ b/src/plugins/data_views/server/fetcher/lib/resolve_time_pattern.ts
@@ -28,7 +28,7 @@ import { callIndexAliasApi } from './es_api';
export async function resolveTimePattern(callCluster: ElasticsearchClient, timePattern: string) {
const aliases = await callIndexAliasApi(callCluster, timePatternToWildcard(timePattern));
- const allIndexDetails = chain(aliases.body)
+ const allIndexDetails = chain(aliases)
.reduce(
(acc: string[], index: any, indexName: string) =>
acc.concat(indexName, Object.keys(index.aliases || {})),
diff --git a/src/plugins/data_views/server/has_user_index_pattern.test.ts b/src/plugins/data_views/server/has_user_index_pattern.test.ts
index aeaa64b949dbc..886fa8c618e90 100644
--- a/src/plugins/data_views/server/has_user_index_pattern.test.ts
+++ b/src/plugins/data_views/server/has_user_index_pattern.test.ts
@@ -69,13 +69,11 @@ describe('hasUserIndexPattern', () => {
});
it('calls indices.resolveIndex for the index patterns', async () => {
- esClient.indices.resolveIndex.mockReturnValue(
- elasticsearchServiceMock.createSuccessTransportRequestPromise({
- indices: [],
- data_streams: [],
- aliases: [],
- })
- );
+ esClient.indices.resolveIndex.mockResponse({
+ indices: [],
+ data_streams: [],
+ aliases: [],
+ });
await hasUserIndexPattern({ esClient, soClient });
expect(esClient.indices.resolveIndex).toHaveBeenCalledWith({
name: 'logs-*,metrics-*',
@@ -83,91 +81,79 @@ describe('hasUserIndexPattern', () => {
});
it('returns false if no logs or metrics data_streams exist', async () => {
- esClient.indices.resolveIndex.mockReturnValue(
- elasticsearchServiceMock.createSuccessTransportRequestPromise({
- indices: [],
- data_streams: [],
- aliases: [],
- })
- );
+ esClient.indices.resolveIndex.mockResponse({
+ indices: [],
+ data_streams: [],
+ aliases: [],
+ });
expect(await hasUserIndexPattern({ esClient, soClient })).toEqual(false);
});
it('returns true if any index exists', async () => {
- esClient.indices.resolveIndex.mockReturnValue(
- elasticsearchServiceMock.createSuccessTransportRequestPromise({
- indices: [{ name: 'logs', attributes: [] }],
- data_streams: [],
- aliases: [],
- })
- );
+ esClient.indices.resolveIndex.mockResponse({
+ indices: [{ name: 'logs', attributes: [] }],
+ data_streams: [],
+ aliases: [],
+ });
expect(await hasUserIndexPattern({ esClient, soClient })).toEqual(true);
});
it('returns false if only metrics-elastic_agent data stream exists', async () => {
- esClient.indices.resolveIndex.mockReturnValue(
- elasticsearchServiceMock.createSuccessTransportRequestPromise({
- indices: [],
- data_streams: [
- {
- name: 'metrics-elastic_agent',
- timestamp_field: '@timestamp',
- backing_indices: ['.ds-metrics-elastic_agent'],
- },
- ],
- aliases: [],
- })
- );
+ esClient.indices.resolveIndex.mockResponse({
+ indices: [],
+ data_streams: [
+ {
+ name: 'metrics-elastic_agent',
+ timestamp_field: '@timestamp',
+ backing_indices: ['.ds-metrics-elastic_agent'],
+ },
+ ],
+ aliases: [],
+ });
expect(await hasUserIndexPattern({ esClient, soClient })).toEqual(false);
});
it('returns false if only logs-elastic_agent data stream exists', async () => {
- esClient.indices.resolveIndex.mockReturnValue(
- elasticsearchServiceMock.createSuccessTransportRequestPromise({
- indices: [],
- data_streams: [
- {
- name: 'logs-elastic_agent',
- timestamp_field: '@timestamp',
- backing_indices: ['.ds-logs-elastic_agent'],
- },
- ],
- aliases: [],
- })
- );
+ esClient.indices.resolveIndex.mockResponse({
+ indices: [],
+ data_streams: [
+ {
+ name: 'logs-elastic_agent',
+ timestamp_field: '@timestamp',
+ backing_indices: ['.ds-logs-elastic_agent'],
+ },
+ ],
+ aliases: [],
+ });
expect(await hasUserIndexPattern({ esClient, soClient })).toEqual(false);
});
it('returns false if only metrics-endpoint.metadata_current_default index exists', async () => {
- esClient.indices.resolveIndex.mockReturnValue(
- elasticsearchServiceMock.createSuccessTransportRequestPromise({
- indices: [
- {
- name: 'metrics-endpoint.metadata_current_default',
- attributes: ['open'],
- },
- ],
- aliases: [],
- data_streams: [],
- })
- );
+ esClient.indices.resolveIndex.mockResponse({
+ indices: [
+ {
+ name: 'metrics-endpoint.metadata_current_default',
+ attributes: ['open'],
+ },
+ ],
+ aliases: [],
+ data_streams: [],
+ });
expect(await hasUserIndexPattern({ esClient, soClient })).toEqual(false);
});
it('returns true if any other data stream exists', async () => {
- esClient.indices.resolveIndex.mockReturnValue(
- elasticsearchServiceMock.createSuccessTransportRequestPromise({
- indices: [],
- data_streams: [
- {
- name: 'other',
- timestamp_field: '@timestamp',
- backing_indices: ['.ds-other'],
- },
- ],
- aliases: [],
- })
- );
+ esClient.indices.resolveIndex.mockResponse({
+ indices: [],
+ data_streams: [
+ {
+ name: 'other',
+ timestamp_field: '@timestamp',
+ backing_indices: ['.ds-other'],
+ },
+ ],
+ aliases: [],
+ });
expect(await hasUserIndexPattern({ esClient, soClient })).toEqual(true);
});
});
diff --git a/src/plugins/data_views/server/has_user_index_pattern.ts b/src/plugins/data_views/server/has_user_index_pattern.ts
index 6566f75ebc52e..cf64a2c2013da 100644
--- a/src/plugins/data_views/server/has_user_index_pattern.ts
+++ b/src/plugins/data_views/server/has_user_index_pattern.ts
@@ -44,13 +44,13 @@ export const hasUserIndexPattern = async ({ esClient, soClient }: Deps): Promise
name: `${FLEET_ASSETS_TO_IGNORE.LOGS_INDEX_PATTERN},${FLEET_ASSETS_TO_IGNORE.METRICS_INDEX_PATTERN}`,
});
- const hasAnyNonDefaultFleetIndices = resolveResponse.body.indices.some(
+ const hasAnyNonDefaultFleetIndices = resolveResponse.indices.some(
(ds) => ds.name !== FLEET_ASSETS_TO_IGNORE.METRICS_ENDPOINT_INDEX_TO_IGNORE
);
if (hasAnyNonDefaultFleetIndices) return true;
- const hasAnyNonDefaultFleetDataStreams = resolveResponse.body.data_streams.some(
+ const hasAnyNonDefaultFleetDataStreams = resolveResponse.data_streams.some(
(ds) =>
ds.name !== FLEET_ASSETS_TO_IGNORE.METRICS_DATA_STREAM_TO_IGNORE &&
ds.name !== FLEET_ASSETS_TO_IGNORE.LOGS_DATA_STREAM_TO_IGNORE
diff --git a/src/plugins/home/server/routes/fetch_es_hits_status.ts b/src/plugins/home/server/routes/fetch_es_hits_status.ts
index 2939fc08712ea..b3cfef51920f1 100644
--- a/src/plugins/home/server/routes/fetch_es_hits_status.ts
+++ b/src/plugins/home/server/routes/fetch_es_hits_status.ts
@@ -25,7 +25,7 @@ export const registerHitsStatusRoute = (router: IRouter) => {
const client = context.core.elasticsearch.client;
try {
- const { body } = await client.asCurrentUser.search({
+ const body = await client.asCurrentUser.search({
index,
size: 1,
body: {
diff --git a/src/plugins/home/server/services/sample_data/lib/insert_data_into_index.ts b/src/plugins/home/server/services/sample_data/lib/insert_data_into_index.ts
index 4a7d7e9813dcc..e22a552b7d7bd 100644
--- a/src/plugins/home/server/services/sample_data/lib/insert_data_into_index.ts
+++ b/src/plugins/home/server/services/sample_data/lib/insert_data_into_index.ts
@@ -54,7 +54,7 @@ export const insertDataIntoIndex = ({
bulk.push(updateTimestamps(doc));
});
- const { body: resp } = await esClient.asCurrentUser.bulk({
+ const resp = await esClient.asCurrentUser.bulk({
body: bulk,
});
diff --git a/src/plugins/home/server/services/sample_data/routes/list.ts b/src/plugins/home/server/services/sample_data/routes/list.ts
index a7ca32341f1f5..6bcc40c0c93e3 100644
--- a/src/plugins/home/server/services/sample_data/routes/list.ts
+++ b/src/plugins/home/server/services/sample_data/routes/list.ts
@@ -68,6 +68,7 @@ export const createListRoute = (
};
type ExistingSampleObjects = Map;
+
async function findExistingSampleObjects(
context: RequestHandlerContext,
logger: Logger,
@@ -104,15 +105,14 @@ async function getSampleDatasetStatus(
const dataIndexConfig = sampleDataset.dataIndices[i];
const index = createIndexName(sampleDataset.id, dataIndexConfig.id);
try {
- const { body: indexExists } =
- await context.core.elasticsearch.client.asCurrentUser.indices.exists({
- index,
- });
+ const indexExists = await context.core.elasticsearch.client.asCurrentUser.indices.exists({
+ index,
+ });
if (!indexExists) {
return { status: NOT_INSTALLED };
}
- const { body: count } = await context.core.elasticsearch.client.asCurrentUser.count({
+ const count = await context.core.elasticsearch.client.asCurrentUser.count({
index,
});
if (count.count === 0) {
diff --git a/src/plugins/home/server/services/sample_data/sample_data_installer.test.ts b/src/plugins/home/server/services/sample_data/sample_data_installer.test.ts
index 22079cbcafdb3..205b00e3df94f 100644
--- a/src/plugins/home/server/services/sample_data/sample_data_installer.test.ts
+++ b/src/plugins/home/server/services/sample_data/sample_data_installer.test.ts
@@ -206,17 +206,13 @@ describe('SampleDataInstaller', () => {
it('deletes the alias and the index', async () => {
const indexName = 'target_index';
- esClient.asCurrentUser.indices.getAlias.mockResolvedValue(
- elasticsearchServiceMock.createApiResponse({
- body: {
- [indexName]: {
- aliases: {
- kibana_sample_data_test_single_data_index: {},
- },
- },
+ esClient.asCurrentUser.indices.getAlias.mockResponse({
+ [indexName]: {
+ aliases: {
+ kibana_sample_data_test_single_data_index: {},
},
- })
- );
+ },
+ });
await installer.install('test_single_data_index');
@@ -301,17 +297,13 @@ describe('SampleDataInstaller', () => {
it('deletes the alias and the index', async () => {
const indexName = 'target_index';
- esClient.asCurrentUser.indices.getAlias.mockResolvedValue(
- elasticsearchServiceMock.createApiResponse({
- body: {
- [indexName]: {
- aliases: {
- kibana_sample_data_test_single_data_index: {},
- },
- },
+ esClient.asCurrentUser.indices.getAlias.mockResponse({
+ [indexName]: {
+ aliases: {
+ kibana_sample_data_test_single_data_index: {},
},
- })
- );
+ },
+ });
await installer.uninstall('test_single_data_index');
diff --git a/src/plugins/home/server/services/sample_data/sample_data_installer.ts b/src/plugins/home/server/services/sample_data/sample_data_installer.ts
index 8e9315719bc16..5aec4a6b2d516 100644
--- a/src/plugins/home/server/services/sample_data/sample_data_installer.ts
+++ b/src/plugins/home/server/services/sample_data/sample_data_installer.ts
@@ -118,7 +118,7 @@ export class SampleDataInstaller {
try {
// if the sample data was reindexed using UA, the index name is actually an alias pointing to the reindexed
// index. In that case, we need to get rid of the alias and to delete the underlying index
- const { body: response } = await this.esClient.asCurrentUser.indices.getAlias({
+ const response = await this.esClient.asCurrentUser.indices.getAlias({
name: index,
});
const aliasName = index;
diff --git a/src/plugins/home/server/services/sample_data/usage/collector_fetch.test.ts b/src/plugins/home/server/services/sample_data/usage/collector_fetch.test.ts
index d2d06433634fa..c37c55bf02535 100644
--- a/src/plugins/home/server/services/sample_data/usage/collector_fetch.test.ts
+++ b/src/plugins/home/server/services/sample_data/usage/collector_fetch.test.ts
@@ -12,7 +12,7 @@ import { fetchProvider } from './collector_fetch';
const getMockFetchClients = (hits?: unknown[]) => {
const fetchParamsMock = createCollectorFetchContextMock();
- fetchParamsMock.esClient.search = jest.fn().mockResolvedValue({ body: { hits: { hits } } });
+ fetchParamsMock.esClient.search = jest.fn().mockResolvedValue({ hits: { hits } });
return fetchParamsMock;
};
diff --git a/src/plugins/home/server/services/sample_data/usage/collector_fetch.ts b/src/plugins/home/server/services/sample_data/usage/collector_fetch.ts
index d8da9b4654152..3342912919a62 100644
--- a/src/plugins/home/server/services/sample_data/usage/collector_fetch.ts
+++ b/src/plugins/home/server/services/sample_data/usage/collector_fetch.ts
@@ -35,7 +35,7 @@ type ESResponse = SearchResponse;
export function fetchProvider(index: string) {
return async ({ esClient }: CollectorFetchContext) => {
- const { body: response } = await esClient.search(
+ const response = await esClient.search(
{
index,
body: {
diff --git a/src/plugins/interactive_setup/server/elasticsearch_service.test.ts b/src/plugins/interactive_setup/server/elasticsearch_service.test.ts
index e7b326a1d019d..63d95673cacb4 100644
--- a/src/plugins/interactive_setup/server/elasticsearch_service.test.ts
+++ b/src/plugins/interactive_setup/server/elasticsearch_service.test.ts
@@ -197,9 +197,7 @@ describe('ElasticsearchService', () => {
});
it('checks connection status only once if connection is known to be configured right from start', async () => {
- mockConnectionStatusClient.asInternalUser.ping.mockResolvedValue(
- interactiveSetupMock.createApiResponse({ body: true })
- );
+ mockConnectionStatusClient.asInternalUser.ping.mockResponse(true);
const mockHandler = jest.fn();
setupContract.connectionStatus$.subscribe(mockHandler);
@@ -410,9 +408,9 @@ describe('ElasticsearchService', () => {
);
mockEnrollClient.asScoped.mockReturnValue(mockEnrollScopedClusterClient);
- mockAuthenticateClient.asInternalUser.security.authenticate.mockResolvedValue(
- interactiveSetupMock.createApiResponse({ statusCode: 200, body: {} as any })
- );
+ mockAuthenticateClient.asInternalUser.security.authenticate.mockResponse({} as any, {
+ statusCode: 200,
+ });
mockCompatibility(false, 'Oh no!');
@@ -457,9 +455,9 @@ describe('ElasticsearchService', () => {
.mockReturnValueOnce(mockHostOneEnrollScopedClusterClient)
.mockReturnValueOnce(mockHostTwoEnrollScopedClusterClient);
- mockAuthenticateClient.asInternalUser.security.authenticate.mockResolvedValue(
- interactiveSetupMock.createApiResponse({ statusCode: 200, body: {} as any })
- );
+ mockAuthenticateClient.asInternalUser.security.authenticate.mockResponse({} as any, {
+ statusCode: 200,
+ });
const expectedCa = `-----BEGIN CERTIFICATE-----
@@ -521,19 +519,25 @@ some weird+ca/with
).toHaveBeenCalledTimes(1);
expect(
mockHostOneEnrollScopedClusterClient.asCurrentUser.transport.request
- ).toHaveBeenCalledWith({
- method: 'GET',
- path: '/_security/enroll/kibana',
- });
+ ).toHaveBeenCalledWith(
+ {
+ method: 'GET',
+ path: '/_security/enroll/kibana',
+ },
+ { meta: true }
+ );
expect(
mockHostTwoEnrollScopedClusterClient.asCurrentUser.transport.request
).toHaveBeenCalledTimes(1);
expect(
mockHostTwoEnrollScopedClusterClient.asCurrentUser.transport.request
- ).toHaveBeenCalledWith({
- method: 'GET',
- path: '/_security/enroll/kibana',
- });
+ ).toHaveBeenCalledWith(
+ {
+ method: 'GET',
+ path: '/_security/enroll/kibana',
+ },
+ { meta: true }
+ );
expect(mockAuthenticateClient.asInternalUser.security.authenticate).toHaveBeenCalledTimes(
1
);
@@ -560,9 +564,7 @@ some weird+ca/with
});
it('fails if version is incompatible', async () => {
- mockAuthenticateClient.asInternalUser.ping.mockResolvedValue(
- interactiveSetupMock.createApiResponse({ statusCode: 200, body: true })
- );
+ mockAuthenticateClient.asInternalUser.ping.mockResponse(true);
mockCompatibility(false, 'Oh no!');
@@ -573,9 +575,7 @@ some weird+ca/with
});
it('succeeds if ping call succeeds', async () => {
- mockAuthenticateClient.asInternalUser.ping.mockResolvedValue(
- interactiveSetupMock.createApiResponse({ statusCode: 200, body: true })
- );
+ mockAuthenticateClient.asInternalUser.ping.mockResponse(true);
await expect(
setupContract.authenticate({ host: 'http://localhost:9200' })
@@ -612,9 +612,8 @@ some weird+ca/with
});
it('fails if host is not Elasticsearch', async () => {
- mockPingClient.asInternalUser.ping.mockResolvedValue(
- interactiveSetupMock.createApiResponse({ statusCode: 200, body: true })
- );
+ mockAuthenticateClient.asInternalUser.ping.mockResponse(true);
+
mockPingClient.asInternalUser.transport.request.mockResolvedValue(
interactiveSetupMock.createApiResponse({ statusCode: 200, body: {}, headers: {} })
);
@@ -626,9 +625,7 @@ some weird+ca/with
});
it('succeeds if host does not require authentication', async () => {
- mockPingClient.asInternalUser.ping.mockResolvedValue(
- interactiveSetupMock.createApiResponse({ statusCode: 200, body: true })
- );
+ mockAuthenticateClient.asInternalUser.ping.mockResponse(true);
await expect(setupContract.ping('http://localhost:9200')).resolves.toEqual({
authRequired: false,
diff --git a/src/plugins/interactive_setup/server/elasticsearch_service.ts b/src/plugins/interactive_setup/server/elasticsearch_service.ts
index 3b5f1532e0b1f..f9bcbd60d02d3 100644
--- a/src/plugins/interactive_setup/server/elasticsearch_service.ts
+++ b/src/plugins/interactive_setup/server/elasticsearch_service.ts
@@ -122,6 +122,7 @@ export class ElasticsearchService {
* Elasticsearch client used to check Elasticsearch connection status.
*/
private connectionStatusClient?: ICustomClusterClient;
+
constructor(private readonly logger: Logger, private kibanaVersion: string) {}
public setup({
@@ -199,10 +200,13 @@ export class ElasticsearchService {
try {
enrollmentResponse = await enrollClient
.asScoped(scopeableRequest)
- .asCurrentUser.transport.request({
- method: 'GET',
- path: '/_security/enroll/kibana',
- });
+ .asCurrentUser.transport.request(
+ {
+ method: 'GET',
+ path: '/_security/enroll/kibana',
+ },
+ { meta: true }
+ );
} catch (err) {
// We expect that all hosts belong to exactly same node and any non-connection error for one host would mean
// that enrollment will fail for any other host and we should bail out.
@@ -357,10 +361,13 @@ export class ElasticsearchService {
this.logger.debug(`Verifying that host "${host}" responds with Elastic product header`);
try {
- const response = await client.asInternalUser.transport.request({
- method: 'OPTIONS',
- path: '/',
- });
+ const response = await client.asInternalUser.transport.request(
+ {
+ method: 'OPTIONS',
+ path: '/',
+ },
+ { meta: true }
+ );
if (response.headers?.['x-elastic-product'] !== 'Elasticsearch') {
throw new Error('Host did not respond with valid Elastic product header.');
}
diff --git a/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts.test.ts b/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts.test.ts
index 4b3421efed96e..8fb75d1ae08e3 100644
--- a/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts.test.ts
+++ b/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts.test.ts
@@ -11,10 +11,8 @@ import { getSavedObjectsCounts } from './get_saved_object_counts';
function mockGetSavedObjectsCounts(params: TBody) {
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- esClient.search.mockResolvedValue(
- // @ts-expect-error we only care about the response body
- { body: { ...params } }
- );
+ // @ts-expect-error arbitrary type
+ esClient.search.mockResponse(params);
return esClient;
}
diff --git a/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts.ts b/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts.ts
index f82a803b763c5..cb3c09efa0e3b 100644
--- a/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts.ts
+++ b/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts.ts
@@ -25,7 +25,7 @@ export async function getSavedObjectsCounts(
aggs: { types: { terms: { field: 'type' } } },
},
};
- const { body } = await esClient.search(savedObjectCountSearchParams);
+ const body = await esClient.search(savedObjectCountSearchParams);
// @ts-expect-error declare type for aggregations explicitly
return body.aggregations?.types?.buckets || [];
}
diff --git a/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/kibana_usage_collector.test.ts b/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/kibana_usage_collector.test.ts
index d61b8ca2c7779..0f5152daa31a7 100644
--- a/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/kibana_usage_collector.test.ts
+++ b/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/kibana_usage_collector.test.ts
@@ -31,7 +31,7 @@ describe('kibana_usage', () => {
const fetchParamsMock = createCollectorFetchContextMock();
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
// @ts-expect-error for the sake of the tests, we only require `hits`
- esClient.search.mockResolvedValue({ body: { hits: { hits } } });
+ esClient.search.mockResponse({ hits: { hits } });
fetchParamsMock.esClient = esClient;
return fetchParamsMock;
};
@@ -58,9 +58,9 @@ describe('kibana_usage', () => {
function mockGetSavedObjectsCounts(params: TBody) {
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- esClient.search.mockResolvedValue(
+ esClient.search.mockResponse(
// @ts-expect-error we only care about the response body
- { body: { ...params } }
+ { ...params }
);
return esClient;
}
diff --git a/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/saved_objects_count_collector.test.ts b/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/saved_objects_count_collector.test.ts
index 1f507dcc44666..a5bda0c0b3713 100644
--- a/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/saved_objects_count_collector.test.ts
+++ b/src/plugins/kibana_usage_collection/server/collectors/saved_objects_counts/saved_objects_count_collector.test.ts
@@ -38,16 +38,14 @@ describe('saved_objects_count_collector', () => {
test('should return some values when the aggregations return something', async () => {
const fetchContextMock = createCollectorFetchContextMock();
fetchContextMock.esClient.search = jest.fn().mockImplementation(() => ({
- body: {
- aggregations: {
- types: {
- buckets: [
- { key: 'type_one', doc_count: 20 },
- { key: 'type_two', doc_count: 45 },
- { key: 'type-three', doc_count: 66 },
- { key: 'type-four', doc_count: 0 },
- ],
- },
+ aggregations: {
+ types: {
+ buckets: [
+ { key: 'type_one', doc_count: 20 },
+ { key: 'type_two', doc_count: 45 },
+ { key: 'type-three', doc_count: 66 },
+ { key: 'type-four', doc_count: 0 },
+ ],
},
},
}));
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_cluster_info.test.ts b/src/plugins/telemetry/server/telemetry_collection/get_cluster_info.test.ts
index cd414beb42182..3c96b45ed3262 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_cluster_info.test.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_cluster_info.test.ts
@@ -12,7 +12,7 @@ import { getClusterInfo } from './get_cluster_info';
export function mockGetClusterInfo(clusterInfo: ClusterInfo) {
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
// @ts-expect-error we only care about the response body
- esClient.info.mockResolvedValue({ body: { ...clusterInfo } });
+ esClient.info.mockResponse({ ...clusterInfo });
return esClient;
}
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_cluster_info.ts b/src/plugins/telemetry/server/telemetry_collection/get_cluster_info.ts
index 3f93bde1e7e62..667b8564e4d33 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_cluster_info.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_cluster_info.ts
@@ -16,6 +16,5 @@ import { ElasticsearchClient } from 'src/core/server';
* @param {function} esClient The asInternalUser handler (exposed for testing)
*/
export async function getClusterInfo(esClient: ElasticsearchClient) {
- const { body } = await esClient.info();
- return body;
+ return await esClient.info();
}
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_cluster_stats.test.ts b/src/plugins/telemetry/server/telemetry_collection/get_cluster_stats.test.ts
index 06d3ebeb7ea0e..84a0fdaacb5b1 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_cluster_stats.test.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_cluster_stats.test.ts
@@ -12,7 +12,7 @@ import { TIMEOUT } from './constants';
describe('get_cluster_stats', () => {
it('uses the esClient to get the response from the `cluster.stats` API', async () => {
- const response = { body: { cluster_uuid: '1234' } };
+ const response = { cluster_uuid: '1234' };
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
esClient.cluster.stats.mockImplementationOnce(
// @ts-expect-error the method only cares about the response body
@@ -22,6 +22,6 @@ describe('get_cluster_stats', () => {
);
const result = await getClusterStats(esClient);
expect(esClient.cluster.stats).toHaveBeenCalledWith({ timeout: TIMEOUT });
- expect(result).toStrictEqual(response.body);
+ expect(result).toStrictEqual(response);
});
});
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_cluster_stats.ts b/src/plugins/telemetry/server/telemetry_collection/get_cluster_stats.ts
index dd5f4f97c6b02..f420291d1c131 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_cluster_stats.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_cluster_stats.ts
@@ -9,14 +9,14 @@
import { ClusterDetailsGetter } from 'src/plugins/telemetry_collection_manager/server';
import { ElasticsearchClient } from 'src/core/server';
import { TIMEOUT } from './constants';
+
/**
* Get the cluster stats from the connected cluster.
*
* This is the equivalent to GET /_cluster/stats?timeout=30s.
*/
export async function getClusterStats(esClient: ElasticsearchClient) {
- const { body } = await esClient.cluster.stats({ timeout: TIMEOUT });
- return body;
+ return await esClient.cluster.stats({ timeout: TIMEOUT });
}
/**
@@ -25,7 +25,6 @@ export async function getClusterStats(esClient: ElasticsearchClient) {
* @param esClient Scoped Elasticsearch client
*/
export const getClusterUuids: ClusterDetailsGetter = async ({ esClient }) => {
- const { body } = await esClient.cluster.stats({ timeout: TIMEOUT });
-
+ const body = await esClient.cluster.stats({ timeout: TIMEOUT });
return [{ clusterUuid: body.cluster_uuid }];
};
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.test.ts b/src/plugins/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.test.ts
index b3a25da0a7abf..310ba6a3ee41d 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.test.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.test.ts
@@ -309,11 +309,11 @@ function mockEsClient(
},
])
);
- return { body };
+ return body;
});
// @ts-expect-error
esClient.indices.stats.mockImplementationOnce(async () => {
- return { body: indexStats };
+ return indexStats;
});
return esClient;
}
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.ts b/src/plugins/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.ts
index 8a0b86cf3b0f0..3f98ead25ff4e 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.ts
@@ -181,59 +181,6 @@ export function buildDataTelemetryPayload(indices: DataTelemetryIndex[]): DataTe
return [...acc.values()];
}
-interface IndexStats {
- indices: {
- [indexName: string]: {
- total: {
- docs: {
- count: number;
- deleted: number;
- };
- store: {
- size_in_bytes: number;
- };
- };
- };
- };
-}
-
-interface IndexMappings {
- [indexName: string]: {
- mappings: {
- _meta?: {
- beat?: string;
-
- // Ingest Manager provided metadata
- package?: {
- name?: string;
- };
- managed_by?: string; // Typically "ingest-manager"
- };
- properties: {
- data_stream?: {
- properties: {
- dataset?: {
- type: string;
- value?: string;
- };
- type?: {
- type: string;
- value?: string;
- };
- };
- };
- ecs?: {
- properties: {
- version?: {
- type: string;
- };
- };
- };
- };
- };
- };
-}
-
export async function getDataTelemetry(esClient: ElasticsearchClient) {
try {
const index = [
@@ -271,9 +218,9 @@ export async function getDataTelemetry(esClient: ElasticsearchClient) {
metric: ['docs', 'store'],
filter_path: ['indices.*.total'],
};
- const [{ body: indexMappings }, { body: indexStats }] = await Promise.all([
- esClient.indices.getMapping(indexMappingsParams),
- esClient.indices.stats(indicesStatsParams),
+ const [indexMappings, indexStats] = await Promise.all([
+ esClient.indices.getMapping(indexMappingsParams),
+ esClient.indices.stats(indicesStatsParams),
]);
const indexNames = Object.keys({ ...indexMappings, ...indexStats?.indices });
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts
index bcff58c3304c7..2392ac570ecbc 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts
@@ -23,50 +23,45 @@ function mockUsageCollection(kibanaUsage = {}) {
usageCollection.toObject = jest.fn().mockImplementation((data) => data);
return usageCollection;
}
+
// set up successful call mocks for info, cluster stats, nodes usage and data telemetry
function mockGetLocalStats(
clusterInfo: ClusterInfo,
clusterStats: ClusterStats
) {
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- esClient.info.mockResolvedValue(
- // @ts-expect-error we only care about the response body
- { body: { ...clusterInfo } }
- );
- esClient.cluster.stats
- // @ts-expect-error we only care about the response body
- .mockResolvedValue({ body: { ...clusterStats } });
// @ts-expect-error we only care about the response body
- esClient.nodes.usage.mockResolvedValue({
- body: {
- cluster_name: 'testCluster',
- nodes: {
- some_node_id: {
- timestamp: 1588617023177,
- since: 1588616945163,
- rest_actions: {
- nodes_usage_action: 1,
- create_index_action: 1,
- document_get_action: 1,
- search_action: 19,
- nodes_info_action: 36,
+ esClient.info.mockResponse({ ...clusterInfo });
+ // @ts-expect-error we only care about the response body
+ esClient.cluster.stats.mockResponse({ ...clusterStats });
+ esClient.nodes.usage.mockResponse({
+ cluster_name: 'testCluster',
+ nodes: {
+ some_node_id: {
+ timestamp: 1588617023177,
+ since: 1588616945163,
+ rest_actions: {
+ nodes_usage_action: 1,
+ create_index_action: 1,
+ document_get_action: 1,
+ search_action: 19,
+ nodes_info_action: 36,
+ },
+ aggregations: {
+ scripted_metric: {
+ other: 7,
},
- aggregations: {
- scripted_metric: {
- other: 7,
- },
- terms: {
- bytes: 2,
- },
+ terms: {
+ bytes: 2,
},
},
},
},
});
// @ts-expect-error we only care about the response body
- esClient.indices.getMapping.mockResolvedValue({ body: { mappings: {} } });
+ esClient.indices.getMapping.mockResponse({ mappings: {} });
// @ts-expect-error we only care about the response body
- esClient.indices.stats.mockResolvedValue({ body: { indices: {} } });
+ esClient.indices.stats.mockResponse({ indices: {} });
return esClient;
}
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.test.ts b/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.test.ts
index 9192afd3376d5..65bb6eed344aa 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.test.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.test.ts
@@ -37,14 +37,11 @@ const mockedNodesFetchResponse = {
describe('get_nodes_usage', () => {
it('returns a modified array of nodes usage data', async () => {
- const response = Promise.resolve({ body: mockedNodesFetchResponse });
+ const response = Promise.resolve(mockedNodesFetchResponse);
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- esClient.nodes.usage.mockImplementationOnce(
- // @ts-expect-error
- async (_params = { timeout: TIMEOUT }) => {
- return response;
- }
- );
+ esClient.nodes.usage.mockImplementationOnce(async (_params = { timeout: TIMEOUT }) => {
+ return response;
+ });
const item = await getNodesUsage(esClient);
expect(esClient.nodes.usage).toHaveBeenCalledWith({ timeout: TIMEOUT });
expect(item).toStrictEqual({
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts b/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts
index a5d4f32b3a62f..b701a696f210d 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts
@@ -32,10 +32,9 @@ export type NodesUsageGetter = (esClient: ElasticsearchClient) => Promise<{ node
export async function fetchNodesUsage(
esClient: ElasticsearchClient
): Promise {
- const { body } = await esClient.nodes.usage({
+ return await esClient.nodes.usage({
timeout: TIMEOUT,
});
- return body;
}
/**
diff --git a/src/plugins/usage_collection/server/routes/stats/stats.ts b/src/plugins/usage_collection/server/routes/stats/stats.ts
index d78f9ab69b66d..8e5382d163172 100644
--- a/src/plugins/usage_collection/server/routes/stats/stats.ts
+++ b/src/plugins/usage_collection/server/routes/stats/stats.ts
@@ -63,7 +63,7 @@ export function registerStatsRoute({
};
const getClusterUuid = async (asCurrentUser: ElasticsearchClient): Promise => {
- const { body } = await asCurrentUser.info({ filter_path: 'cluster_uuid' });
+ const body = await asCurrentUser.info({ filter_path: 'cluster_uuid' });
const { cluster_uuid: uuid } = body;
return uuid;
};
diff --git a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.test.ts b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.test.ts
index 4d2608e3519ed..b74bb97c3d649 100644
--- a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.test.ts
+++ b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.test.ts
@@ -118,7 +118,7 @@ describe('Rollup Search Strategy', () => {
});
test('should return rollup data', async () => {
- rollupResolvedData = Promise.resolve({ body: 'data' });
+ rollupResolvedData = Promise.resolve('data');
const rollupData = await rollupSearchStrategy.getRollupData(requestContext, indexPattern);
diff --git a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts
index 2508c68066017..4d6d9d832a2e0 100644
--- a/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts
+++ b/src/plugins/vis_types/timeseries/server/lib/search_strategies/strategies/rollup_search_strategy.ts
@@ -40,7 +40,7 @@ export class RollupSearchStrategy extends AbstractSearchStrategy {
indexPattern: string
) {
try {
- const { body } =
+ const body =
await requestContext.core.elasticsearch.client.asCurrentUser.rollup.getRollupIndexCaps({
index: indexPattern,
});
diff --git a/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts b/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts
index 6701ff97cca80..c65690e8532fd 100644
--- a/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts
+++ b/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts
@@ -23,7 +23,7 @@ export class CorePluginAPlugin implements Plugin {
(context) => {
return {
ping: async () => {
- const { body } = await context.core.elasticsearch.client.asInternalUser.ping();
+ const body = await context.core.elasticsearch.client.asInternalUser.ping();
return String(body);
},
};
diff --git a/test/plugin_functional/plugins/core_plugin_execution_context/server/plugin.ts b/test/plugin_functional/plugins/core_plugin_execution_context/server/plugin.ts
index 48889c6d4a455..530b90eb5e6d0 100644
--- a/test/plugin_functional/plugins/core_plugin_execution_context/server/plugin.ts
+++ b/test/plugin_functional/plugins/core_plugin_execution_context/server/plugin.ts
@@ -20,12 +20,16 @@ export class CorePluginExecutionContext implements Plugin {
},
},
async (context, request, response) => {
- const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping();
+ const { headers } = await context.core.elasticsearch.client.asCurrentUser.ping(
+ {},
+ { meta: true }
+ );
return response.ok({ body: headers || {} });
}
);
}
public start() {}
+
public stop() {}
}
diff --git a/test/plugin_functional/plugins/elasticsearch_client_plugin/server/plugin.ts b/test/plugin_functional/plugins/elasticsearch_client_plugin/server/plugin.ts
index 70b4d3590c8db..ab046ab6a0131 100644
--- a/test/plugin_functional/plugins/elasticsearch_client_plugin/server/plugin.ts
+++ b/test/plugin_functional/plugins/elasticsearch_client_plugin/server/plugin.ts
@@ -15,7 +15,7 @@ export class ElasticsearchClientPlugin implements Plugin {
router.get(
{ path: '/api/elasticsearch_client_plugin/context/ping', validate: false },
async (context, req, res) => {
- const { body } = await context.core.elasticsearch.client.asInternalUser.ping();
+ const body = await context.core.elasticsearch.client.asInternalUser.ping();
return res.ok({ body: JSON.stringify(body) });
}
);
@@ -23,14 +23,14 @@ export class ElasticsearchClientPlugin implements Plugin {
{ path: '/api/elasticsearch_client_plugin/contract/ping', validate: false },
async (context, req, res) => {
const [coreStart] = await core.getStartServices();
- const { body } = await coreStart.elasticsearch.client.asInternalUser.ping();
+ const body = await coreStart.elasticsearch.client.asInternalUser.ping();
return res.ok({ body: JSON.stringify(body) });
}
);
router.get(
{ path: '/api/elasticsearch_client_plugin/custom_client/ping', validate: false },
async (context, req, res) => {
- const { body } = await this.client!.asInternalUser.ping();
+ const body = await this.client!.asInternalUser.ping();
return res.ok({ body: JSON.stringify(body) });
}
);
diff --git a/x-pack/plugins/actions/server/actions_client.test.ts b/x-pack/plugins/actions/server/actions_client.test.ts
index 18e405f70c859..c73809cc33773 100644
--- a/x-pack/plugins/actions/server/actions_client.test.ts
+++ b/x-pack/plugins/actions/server/actions_client.test.ts
@@ -35,8 +35,6 @@ import {
} from './authorization/get_authorization_mode_by_source';
import { actionsAuthorizationMock } from './authorization/actions_authorization.mock';
import { trackLegacyRBACExemption } from './lib/track_legacy_rbac_exemption';
-// eslint-disable-next-line @kbn/eslint/no-restricted-paths
-import { elasticsearchClientMock } from '../../../../src/core/server/elasticsearch/client/mocks';
import { ConnectorTokenClient } from './builtin_action_types/lib/connector_token_client';
import { encryptedSavedObjectsMock } from '../../encrypted_saved_objects/server/mocks';
import { Logger } from 'kibana/server';
@@ -847,14 +845,14 @@ describe('getAll()', () => {
],
};
unsecuredSavedObjectsClient.find.mockResolvedValueOnce(expectedResult);
- scopedClusterClient.asInternalUser.search.mockResolvedValueOnce(
+ scopedClusterClient.asInternalUser.search.mockResponse(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
'1': { doc_count: 6 },
testPreconfigured: { doc_count: 2 },
},
- })
+ }
);
actionsClient = new ActionsClient({
@@ -924,14 +922,14 @@ describe('getAll()', () => {
},
],
});
- scopedClusterClient.asInternalUser.search.mockResolvedValueOnce(
+ scopedClusterClient.asInternalUser.search.mockResponse(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
'1': { doc_count: 6 },
testPreconfigured: { doc_count: 2 },
},
- })
+ }
);
await actionsClient.getAll();
@@ -986,14 +984,14 @@ describe('getAll()', () => {
],
};
unsecuredSavedObjectsClient.find.mockResolvedValueOnce(expectedResult);
- scopedClusterClient.asInternalUser.search.mockResolvedValueOnce(
+ scopedClusterClient.asInternalUser.search.mockResponse(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
'1': { doc_count: 6 },
testPreconfigured: { doc_count: 2 },
},
- })
+ }
);
actionsClient = new ActionsClient({
@@ -1063,14 +1061,14 @@ describe('getBulk()', () => {
},
],
});
- scopedClusterClient.asInternalUser.search.mockResolvedValueOnce(
+ scopedClusterClient.asInternalUser.search.mockResponse(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
'1': { doc_count: 6 },
testPreconfigured: { doc_count: 2 },
},
- })
+ }
);
actionsClient = new ActionsClient({
@@ -1137,14 +1135,14 @@ describe('getBulk()', () => {
},
],
});
- scopedClusterClient.asInternalUser.search.mockResolvedValueOnce(
+ scopedClusterClient.asInternalUser.search.mockResponse(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
'1': { doc_count: 6 },
testPreconfigured: { doc_count: 2 },
},
- })
+ }
);
await actionsClient.getBulk(['1']);
@@ -1196,14 +1194,14 @@ describe('getBulk()', () => {
},
],
});
- scopedClusterClient.asInternalUser.search.mockResolvedValueOnce(
+ scopedClusterClient.asInternalUser.search.mockResponse(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
'1': { doc_count: 6 },
testPreconfigured: { doc_count: 2 },
},
- })
+ }
);
actionsClient = new ActionsClient({
diff --git a/x-pack/plugins/actions/server/actions_client.ts b/x-pack/plugins/actions/server/actions_client.ts
index 7d753a9106a1d..18e67c5ca8076 100644
--- a/x-pack/plugins/actions/server/actions_client.ts
+++ b/x-pack/plugins/actions/server/actions_client.ts
@@ -606,7 +606,7 @@ async function injectExtraFindData(
},
};
}
- const { body: aggregationResult } = await scopedClusterClient.asInternalUser.search({
+ const aggregationResult = await scopedClusterClient.asInternalUser.search({
index: defaultKibanaIndex,
body: {
aggs,
diff --git a/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts b/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts
index 50a1deba5af20..7f9aa2298fc14 100644
--- a/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts
+++ b/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts
@@ -559,36 +559,34 @@ describe('execute()', () => {
const scopedClusterClient = elasticsearchClientMock
.createClusterClient()
.asScoped().asCurrentUser;
- scopedClusterClient.bulk.mockResolvedValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- took: 0,
- errors: true,
- items: [
- {
- index: {
- _index: 'indexme',
- _id: '7buTjHQB0SuNSiS9Hayt',
- status: 400,
- error: {
- type: 'mapper_parsing_exception',
- reason: 'failed to parse',
- caused_by: {
- type: 'illegal_argument_exception',
- reason: 'field name cannot be an empty string',
- },
+ scopedClusterClient.bulk.mockResponse({
+ took: 0,
+ errors: true,
+ items: [
+ {
+ index: {
+ _index: 'indexme',
+ _id: '7buTjHQB0SuNSiS9Hayt',
+ status: 400,
+ error: {
+ type: 'mapper_parsing_exception',
+ reason: 'failed to parse',
+ caused_by: {
+ type: 'illegal_argument_exception',
+ reason: 'field name cannot be an empty string',
},
},
},
- ],
- })
- );
+ },
+ ],
+ });
expect(await actionType.executor({ actionId, config, secrets, params, services }))
.toMatchInlineSnapshot(`
Object {
"actionId": "some-id",
"message": "error indexing documents",
- "serviceMessage": "Cannot destructure property 'body' of '(intermediate value)' as it is undefined.",
+ "serviceMessage": "Cannot read properties of undefined (reading 'items')",
"status": "error",
}
`);
diff --git a/x-pack/plugins/actions/server/builtin_action_types/es_index.ts b/x-pack/plugins/actions/server/builtin_action_types/es_index.ts
index 3662fea00e31d..6ab24293d18ad 100644
--- a/x-pack/plugins/actions/server/builtin_action_types/es_index.ts
+++ b/x-pack/plugins/actions/server/builtin_action_types/es_index.ts
@@ -100,7 +100,7 @@ async function executor(
};
try {
- const { body: result } = await services.scopedClusterClient.bulk(bulkParams);
+ const result = await services.scopedClusterClient.bulk(bulkParams);
const err = find(result.items, 'index.error.reason');
if (err) {
diff --git a/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts b/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts
index b80a8d092118a..6d3647be4b65d 100644
--- a/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts
+++ b/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts
@@ -11,7 +11,6 @@ import { spacesMock } from '../../../spaces/server/mocks';
import { CleanupTasksOpts, cleanupTasks } from './cleanup_tasks';
import { TaskInstance } from '../../../task_manager/server';
import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
-import { TransportResult } from '@elastic/elasticsearch';
describe('cleanupTasks', () => {
const logger = loggingSystemMock.create().get();
@@ -70,19 +69,27 @@ describe('cleanupTasks', () => {
});
it('should delete action_task_params and task objects', async () => {
- esClient.bulk.mockResolvedValue({
- body: { items: [], errors: false, took: 1 },
- } as unknown as TransportResult);
+ esClient.bulk.mockResponse({
+ items: [],
+ errors: false,
+ took: 1,
+ } as unknown as estypes.BulkResponse);
const result = await cleanupTasks({
...cleanupTasksOpts,
tasks: [taskSO],
});
- expect(esClient.bulk).toHaveBeenCalledWith({
- body: [{ delete: { _index: cleanupTasksOpts.kibanaIndex, _id: 'action_task_params:123' } }],
- });
- expect(esClient.bulk).toHaveBeenCalledWith({
- body: [{ delete: { _index: cleanupTasksOpts.taskManagerIndex, _id: 'task:123' } }],
- });
+ expect(esClient.bulk).toHaveBeenCalledWith(
+ {
+ body: [{ delete: { _index: cleanupTasksOpts.kibanaIndex, _id: 'action_task_params:123' } }],
+ },
+ { meta: true }
+ );
+ expect(esClient.bulk).toHaveBeenCalledWith(
+ {
+ body: [{ delete: { _index: cleanupTasksOpts.taskManagerIndex, _id: 'task:123' } }],
+ },
+ { meta: true }
+ );
expect(result).toEqual({
success: true,
successCount: 1,
@@ -91,33 +98,37 @@ describe('cleanupTasks', () => {
});
it('should not delete the task if the action_task_params failed to delete', async () => {
- esClient.bulk.mockResolvedValue({
- body: {
- items: [
- {
- delete: {
- _index: cleanupTasksOpts.kibanaIndex,
- _id: 'action_task_params:123',
- status: 500,
- result: 'Failure',
- error: true,
- },
+ esClient.bulk.mockResponse({
+ items: [
+ {
+ delete: {
+ _index: cleanupTasksOpts.kibanaIndex,
+ _id: 'action_task_params:123',
+ status: 500,
+ result: 'Failure',
+ error: true,
},
- ],
- errors: true,
- took: 1,
- },
- } as unknown as TransportResult);
+ },
+ ],
+ errors: true,
+ took: 1,
+ } as unknown as estypes.BulkResponse);
const result = await cleanupTasks({
...cleanupTasksOpts,
tasks: [taskSO],
});
- expect(esClient.bulk).toHaveBeenCalledWith({
- body: [{ delete: { _index: cleanupTasksOpts.kibanaIndex, _id: 'action_task_params:123' } }],
- });
- expect(esClient.bulk).not.toHaveBeenCalledWith({
- body: [{ delete: { _index: cleanupTasksOpts.taskManagerIndex, _id: 'task:123' } }],
- });
+ expect(esClient.bulk).toHaveBeenCalledWith(
+ {
+ body: [{ delete: { _index: cleanupTasksOpts.kibanaIndex, _id: 'action_task_params:123' } }],
+ },
+ { meta: true }
+ );
+ expect(esClient.bulk).not.toHaveBeenCalledWith(
+ {
+ body: [{ delete: { _index: cleanupTasksOpts.taskManagerIndex, _id: 'task:123' } }],
+ },
+ { meta: true }
+ );
expect(result).toEqual({
success: false,
successCount: 0,
diff --git a/x-pack/plugins/actions/server/cleanup_failed_executions/lib/bulk_delete.ts b/x-pack/plugins/actions/server/cleanup_failed_executions/lib/bulk_delete.ts
index 5bbb48a3d520d..c93cc12b49731 100644
--- a/x-pack/plugins/actions/server/cleanup_failed_executions/lib/bulk_delete.ts
+++ b/x-pack/plugins/actions/server/cleanup_failed_executions/lib/bulk_delete.ts
@@ -18,9 +18,12 @@ export async function bulkDelete(
return;
}
- return await esClient.bulk({
- body: ids.map((id) => ({
- delete: { _index: index, _id: id },
- })),
- });
+ return await esClient.bulk(
+ {
+ body: ids.map((id) => ({
+ delete: { _index: index, _id: id },
+ })),
+ },
+ { meta: true }
+ );
}
diff --git a/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.test.ts b/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.test.ts
index a7038d8dc62eb..4a7c5908963f6 100644
--- a/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.test.ts
+++ b/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.test.ts
@@ -5,9 +5,7 @@
* 2.0.
*/
-import { ElasticsearchClient } from 'src/core/server';
import { elasticsearchServiceMock, loggingSystemMock } from 'src/core/server/mocks';
-import { DeeplyMockedKeys } from '@kbn/utility-types/jest';
import {
createAlertHistoryIndexTemplate,
getAlertHistoryIndexTemplate,
@@ -17,19 +15,15 @@ type MockedLogger = ReturnType;
describe('createAlertHistoryIndexTemplate', () => {
let logger: MockedLogger;
- let clusterClient: DeeplyMockedKeys;
+ let clusterClient: ReturnType;
beforeEach(() => {
logger = loggingSystemMock.createLogger();
- clusterClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
+ clusterClient = elasticsearchServiceMock.createElasticsearchClient();
});
test(`should create index template if it doesn't exist`, async () => {
- // Response type for existsIndexTemplate is still TODO
- clusterClient.indices.existsIndexTemplate.mockResolvedValue({
- body: false,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- } as any);
+ clusterClient.indices.existsIndexTemplate.mockResponse(false);
await createAlertHistoryIndexTemplate({ client: clusterClient, logger });
expect(clusterClient.indices.putIndexTemplate).toHaveBeenCalledWith({
@@ -40,11 +34,7 @@ describe('createAlertHistoryIndexTemplate', () => {
});
test(`shouldn't create index template if it already exists`, async () => {
- // Response type for existsIndexTemplate is still TODO
- clusterClient.indices.existsIndexTemplate.mockResolvedValue({
- body: true,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- } as any);
+ clusterClient.indices.existsIndexTemplate.mockResponse(true);
await createAlertHistoryIndexTemplate({ client: clusterClient, logger });
expect(clusterClient.indices.putIndexTemplate).not.toHaveBeenCalled();
diff --git a/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts b/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts
index 28b904361e677..bf3c4ff18e570 100644
--- a/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts
+++ b/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts
@@ -33,14 +33,11 @@ async function doesIndexTemplateExist({
client: ElasticsearchClient;
templateName: string;
}) {
- let result;
try {
- result = (await client.indices.existsIndexTemplate({ name: templateName })).body;
+ return await client.indices.existsIndexTemplate({ name: templateName });
} catch (err) {
throw new Error(`error checking existence of index template: ${err.message}`);
}
-
- return result;
}
async function createIndexTemplate({
diff --git a/x-pack/plugins/actions/server/usage/actions_telemetry.test.ts b/x-pack/plugins/actions/server/usage/actions_telemetry.test.ts
index 07f7f83333844..c389529aa7e82 100644
--- a/x-pack/plugins/actions/server/usage/actions_telemetry.test.ts
+++ b/x-pack/plugins/actions/server/usage/actions_telemetry.test.ts
@@ -12,9 +12,9 @@ import { getExecutionsPerDayCount, getInUseTotalCount, getTotalCount } from './a
describe('actions telemetry', () => {
test('getTotalCount should replace first symbol . to __ for action types names', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValue(
+ mockEsClient.search.mockResponse(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
byActionTypeId: {
value: {
@@ -95,7 +95,7 @@ describe('actions telemetry', () => {
},
],
},
- })
+ }
);
const telemetry = await getTotalCount(mockEsClient, 'test');
@@ -116,9 +116,9 @@ Object {
test('getInUseTotalCount', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValueOnce(
+ mockEsClient.search.mockResponseOnce(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
refs: {
actionRefIds: {
@@ -132,36 +132,35 @@ Object {
hits: [],
},
},
- })
+ }
);
- mockEsClient.search.mockReturnValueOnce(
- // @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- hits: {
- hits: [
- {
- _source: {
- action: {
- id: '1',
- actionTypeId: '.server-log',
- },
- namespaces: ['default'],
+ mockEsClient.search.mockResponse({
+ hits: {
+ hits: [
+ // @ts-expect-error not full search response
+ {
+ _source: {
+ action: {
+ id: '1',
+ actionTypeId: '.server-log',
},
+ namespaces: ['default'],
},
- {
- _source: {
- action: {
- id: '2',
- actionTypeId: '.slack',
- },
- namespaces: ['default'],
+ },
+ // @ts-expect-error not full search response
+ {
+ _source: {
+ action: {
+ id: '2',
+ actionTypeId: '.slack',
},
+ namespaces: ['default'],
},
- ],
- },
- })
- );
+ },
+ ],
+ },
+ });
const telemetry = await getInUseTotalCount(mockEsClient, 'test');
expect(mockEsClient.search).toHaveBeenCalledTimes(2);
@@ -181,9 +180,9 @@ Object {
test('getInUseTotalCount should count preconfigured alert history connector usage', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValueOnce(
+ mockEsClient.search.mockResponseOnce(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
refs: {
actionRefIds: {
@@ -211,35 +210,34 @@ Object {
},
},
},
- })
+ }
);
- mockEsClient.search.mockReturnValueOnce(
- // @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- hits: {
- hits: [
- {
- _source: {
- action: {
- id: '1',
- actionTypeId: '.server-log',
- },
- namespaces: ['default'],
+ mockEsClient.search.mockResponseOnce({
+ hits: {
+ hits: [
+ // @ts-expect-error not full search response
+ {
+ _source: {
+ action: {
+ id: '1',
+ actionTypeId: '.server-log',
},
+ namespaces: ['default'],
},
- {
- _source: {
- action: {
- id: '2',
- actionTypeId: '.slack',
- },
- namespaces: ['default'],
+ },
+ // @ts-expect-error not full search response
+ {
+ _source: {
+ action: {
+ id: '2',
+ actionTypeId: '.slack',
},
+ namespaces: ['default'],
},
- ],
- },
- })
- );
+ },
+ ],
+ },
+ });
const telemetry = await getInUseTotalCount(mockEsClient, 'test', undefined, [
{
id: 'test',
@@ -281,9 +279,9 @@ Object {
test('getTotalCount accounts for preconfigured connectors', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValue(
+ mockEsClient.search.mockResponse(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
byActionTypeId: {
value: {
@@ -364,7 +362,7 @@ Object {
},
],
},
- })
+ }
);
const telemetry = await getTotalCount(mockEsClient, 'test', [
{
@@ -401,9 +399,9 @@ Object {
test('getInUseTotalCount() accounts for preconfigured connectors', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValueOnce(
+ mockEsClient.search.mockResponseOnce(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
refs: {
actionRefIds: {
@@ -439,44 +437,44 @@ Object {
},
},
},
- })
+ }
);
- mockEsClient.search.mockReturnValueOnce(
- // @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- hits: {
- hits: [
- {
- _source: {
- action: {
- id: '1',
- actionTypeId: '.server-log',
- },
- namespaces: ['default'],
+ mockEsClient.search.mockResponseOnce({
+ hits: {
+ hits: [
+ // @ts-expect-error not full search response
+ {
+ _source: {
+ action: {
+ id: '1',
+ actionTypeId: '.server-log',
},
+ namespaces: ['default'],
},
- {
- _source: {
- action: {
- id: '2',
- actionTypeId: '.slack',
- },
- namespaces: ['default'],
+ },
+ // @ts-expect-error not full search response
+ {
+ _source: {
+ action: {
+ id: '2',
+ actionTypeId: '.slack',
},
+ namespaces: ['default'],
},
- {
- _source: {
- action: {
- id: '3',
- actionTypeId: '.email',
- },
- namespaces: ['default'],
+ },
+ // @ts-expect-error not full search response
+ {
+ _source: {
+ action: {
+ id: '3',
+ actionTypeId: '.email',
},
+ namespaces: ['default'],
},
- ],
- },
- })
- );
+ },
+ ],
+ },
+ });
const telemetry = await getInUseTotalCount(mockEsClient, 'test', undefined, [
{
id: 'anotherServerLog',
@@ -508,9 +506,9 @@ Object {
test('getInUseTotalCount() accounts for actions namespaces', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValueOnce(
+ mockEsClient.search.mockResponseOnce(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
refs: {
actionRefIds: {
@@ -546,44 +544,44 @@ Object {
},
},
},
- })
+ }
);
- mockEsClient.search.mockReturnValueOnce(
- // @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- hits: {
- hits: [
- {
- _source: {
- action: {
- id: '1',
- actionTypeId: '.server-log',
- },
- namespaces: ['test'],
+ mockEsClient.search.mockResponseOnce({
+ hits: {
+ hits: [
+ // @ts-expect-error not full search response
+ {
+ _source: {
+ action: {
+ id: '1',
+ actionTypeId: '.server-log',
},
+ namespaces: ['test'],
},
- {
- _source: {
- action: {
- id: '2',
- actionTypeId: '.slack',
- },
- namespaces: ['default'],
+ },
+ // @ts-expect-error not full search response
+ {
+ _source: {
+ action: {
+ id: '2',
+ actionTypeId: '.slack',
},
+ namespaces: ['default'],
},
- {
- _source: {
- action: {
- id: '3',
- actionTypeId: '.email',
- },
- namespaces: ['test2'],
+ },
+ // @ts-expect-error not full search response
+ {
+ _source: {
+ action: {
+ id: '3',
+ actionTypeId: '.email',
},
+ namespaces: ['test2'],
},
- ],
- },
- })
- );
+ },
+ ],
+ },
+ });
const telemetry = await getInUseTotalCount(mockEsClient, 'test');
expect(mockEsClient.search).toHaveBeenCalledTimes(2);
@@ -607,9 +605,9 @@ Object {
test('getExecutionsTotalCount', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValueOnce(
+ mockEsClient.search.mockResponseOnce(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
totalExecutions: {
byConnectorTypeId: {
@@ -668,17 +666,17 @@ Object {
},
},
},
- })
+ }
);
// for .slack connectors
- mockEsClient.search.mockReturnValueOnce(
+ mockEsClient.search.mockResponseOnce(
// @ts-expect-error not full search response
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
avgDuration: { value: 10 },
},
- })
+ }
);
const telemetry = await getExecutionsPerDayCount(mockEsClient, 'test');
diff --git a/x-pack/plugins/actions/server/usage/actions_telemetry.ts b/x-pack/plugins/actions/server/usage/actions_telemetry.ts
index d288611af5e21..473c440ed37fb 100644
--- a/x-pack/plugins/actions/server/usage/actions_telemetry.ts
+++ b/x-pack/plugins/actions/server/usage/actions_telemetry.ts
@@ -41,7 +41,7 @@ export async function getTotalCount(
},
};
- const { body: searchResult } = await esClient.search({
+ const searchResult = await esClient.search({
index: kibanaIndex,
size: 0,
body: {
@@ -223,7 +223,7 @@ export async function getInUseTotalCount(
});
}
- const { body: actionResults } = await esClient.search({
+ const actionResults = await esClient.search({
index: kibanaIndex,
size: 0,
body: {
@@ -268,9 +268,7 @@ export async function getInUseTotalCount(
// @ts-expect-error aggegation type is not specified
actionResults.aggregations.preconfigured_actions?.preconfiguredActionRefIds.value;
- const {
- body: { hits: actions },
- } = await esClient.search<{
+ const { hits: actions } = await esClient.search<{
action: ActionResult;
namespaces: string[];
}>({
@@ -394,8 +392,8 @@ export async function getExecutionsPerDayCount(
scripted_metric: {
init_script: 'state.connectorTypes = [:]; state.total = 0;',
map_script: `
- if (doc['kibana.saved_objects.type'].value == 'action') {
- String connectorType = doc['kibana.saved_objects.type_id'].value;
+ if (doc['kibana.saved_objects.type'].value == 'action') {
+ String connectorType = doc['kibana.saved_objects.type_id'].value;
state.connectorTypes.put(connectorType, state.connectorTypes.containsKey(connectorType) ? state.connectorTypes.get(connectorType) + 1 : 1);
state.total++;
}
@@ -424,7 +422,7 @@ export async function getExecutionsPerDayCount(
},
};
- const { body: actionResults } = await esClient.search({
+ const actionResults = await esClient.search({
index: eventLogIndex,
size: 0,
body: {
diff --git a/x-pack/plugins/alerting/server/lib/create_abortable_es_client_factory.test.ts b/x-pack/plugins/alerting/server/lib/create_abortable_es_client_factory.test.ts
index ed334e262a3a2..d6ac850e59214 100644
--- a/x-pack/plugins/alerting/server/lib/create_abortable_es_client_factory.test.ts
+++ b/x-pack/plugins/alerting/server/lib/create_abortable_es_client_factory.test.ts
@@ -32,6 +32,7 @@ describe('createAbortableEsClientFactory', () => {
await abortableSearchClient.asInternalUser.search(esQuery);
expect(scopedClusterClient.asInternalUser.search).toHaveBeenCalledWith(esQuery, {
signal: abortController.signal,
+ meta: true,
});
expect(scopedClusterClient.asCurrentUser.search).not.toHaveBeenCalled();
});
@@ -47,6 +48,7 @@ describe('createAbortableEsClientFactory', () => {
await abortableSearchClient.asCurrentUser.search(esQuery);
expect(scopedClusterClient.asCurrentUser.search).toHaveBeenCalledWith(esQuery, {
signal: abortController.signal,
+ meta: true,
});
expect(scopedClusterClient.asInternalUser.search).not.toHaveBeenCalled();
});
@@ -63,6 +65,7 @@ describe('createAbortableEsClientFactory', () => {
expect(scopedClusterClient.asInternalUser.search).toHaveBeenCalledWith(esQuery, {
ignore: [404],
signal: abortController.signal,
+ meta: true,
});
expect(scopedClusterClient.asCurrentUser.search).not.toHaveBeenCalled();
});
diff --git a/x-pack/plugins/alerting/server/lib/create_abortable_es_client_factory.ts b/x-pack/plugins/alerting/server/lib/create_abortable_es_client_factory.ts
index ded375c7de9d4..a24ad544557d6 100644
--- a/x-pack/plugins/alerting/server/lib/create_abortable_es_client_factory.ts
+++ b/x-pack/plugins/alerting/server/lib/create_abortable_es_client_factory.ts
@@ -24,6 +24,7 @@ export interface IAbortableClusterClient {
readonly asInternalUser: IAbortableEsClient;
readonly asCurrentUser: IAbortableEsClient;
}
+
export interface CreateAbortableEsClientFactoryOpts {
scopedClusterClient: IScopedClusterClient;
abortController: AbortController;
@@ -42,6 +43,7 @@ export function createAbortableEsClientFactory(opts: CreateAbortableEsClientFact
return await scopedClusterClient.asInternalUser.search(query, {
...searchOptions,
signal: abortController.signal,
+ meta: true,
});
} catch (e) {
if (abortController.signal.aborted) {
@@ -61,6 +63,7 @@ export function createAbortableEsClientFactory(opts: CreateAbortableEsClientFact
return await scopedClusterClient.asCurrentUser.search(query, {
...searchOptions,
signal: abortController.signal,
+ meta: true,
});
} catch (e) {
if (abortController.signal.aborted) {
diff --git a/x-pack/plugins/alerting/server/usage/alerting_telemetry.test.ts b/x-pack/plugins/alerting/server/usage/alerting_telemetry.test.ts
index d679c140733c2..4e34fc2a04f30 100644
--- a/x-pack/plugins/alerting/server/usage/alerting_telemetry.test.ts
+++ b/x-pack/plugins/alerting/server/usage/alerting_telemetry.test.ts
@@ -20,9 +20,9 @@ import {
describe('alerting telemetry', () => {
test('getTotalCountInUse should replace "." symbols with "__" in rule types names', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValue(
+ mockEsClient.search.mockResponse(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
byRuleTypeId: {
value: {
@@ -40,7 +40,7 @@ describe('alerting telemetry', () => {
hits: {
hits: [],
},
- })
+ }
);
const telemetry = await getTotalCountInUse(mockEsClient, 'test');
@@ -62,9 +62,9 @@ Object {
test('getTotalCountAggregations should return min/max connectors in use', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValue(
+ mockEsClient.search.mockResponse(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
byRuleTypeId: {
value: {
@@ -88,7 +88,7 @@ Object {
hits: {
hits: [],
},
- })
+ }
);
const telemetry = await getTotalCountAggregations(mockEsClient, 'test');
@@ -135,9 +135,9 @@ Object {
test('getExecutionsPerDayCount should return execution aggregations for total count, count by rule type and number of failed executions', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValue(
+ mockEsClient.search.mockResponse(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
byRuleTypeId: {
value: {
@@ -169,7 +169,7 @@ Object {
hits: {
hits: [],
},
- })
+ }
);
const telemetry = await getExecutionsPerDayCount(mockEsClient, 'test');
@@ -205,9 +205,9 @@ Object {
test('getExecutionTimeoutsPerDayCount should return execution aggregations for total timeout count and count by rule type', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValue(
+ mockEsClient.search.mockResponse(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
byRuleTypeId: {
value: {
@@ -222,7 +222,7 @@ Object {
hits: {
hits: [],
},
- })
+ }
);
const telemetry = await getExecutionTimeoutsPerDayCount(mockEsClient, 'test');
@@ -241,9 +241,9 @@ Object {
test('getFailedAndUnrecognizedTasksPerDay should aggregations for total count, count by status and count by status and rule type for failed and unrecognized tasks', async () => {
const mockEsClient = elasticsearchClientMock.createClusterClient().asScoped().asInternalUser;
- mockEsClient.search.mockReturnValue(
+ mockEsClient.search.mockResponse(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
- elasticsearchClientMock.createSuccessTransportRequestPromise({
+ {
aggregations: {
byTaskTypeId: {
value: {
@@ -263,7 +263,7 @@ Object {
hits: {
hits: [],
},
- })
+ }
);
const telemetry = await getFailedAndUnrecognizedTasksPerDay(mockEsClient, 'test');
diff --git a/x-pack/plugins/alerting/server/usage/alerting_telemetry.ts b/x-pack/plugins/alerting/server/usage/alerting_telemetry.ts
index 15d6650b2cb4b..b77083c62f000 100644
--- a/x-pack/plugins/alerting/server/usage/alerting_telemetry.ts
+++ b/x-pack/plugins/alerting/server/usage/alerting_telemetry.ts
@@ -43,7 +43,7 @@ const ruleTypeExecutionsWithDurationMetric = {
init_script: 'state.ruleTypes = [:]; state.ruleTypesDuration = [:];',
map_script: `
String ruleType = doc['rule.category'].value;
- long duration = doc['event.duration'].value / (1000 * 1000);
+ long duration = doc['event.duration'].value / (1000 * 1000);
state.ruleTypes.put(ruleType, state.ruleTypes.containsKey(ruleType) ? state.ruleTypes.get(ruleType) + 1 : 1);
state.ruleTypesDuration.put(ruleType, state.ruleTypesDuration.containsKey(ruleType) ? state.ruleTypesDuration.get(ruleType) + duration : duration);
`,
@@ -125,12 +125,12 @@ const ruleTypeFailureExecutionsMetric = {
scripted_metric: {
init_script: 'state.reasons = [:]',
map_script: `
- if (doc['event.outcome'].value == 'failure') {
- String reason = doc['event.reason'].value;
- String ruleType = doc['rule.category'].value;
- Map ruleTypes = state.reasons.containsKey(reason) ? state.reasons.get(reason) : [:];
- ruleTypes.put(ruleType, ruleTypes.containsKey(ruleType) ? ruleTypes.get(ruleType) + 1 : 1);
- state.reasons.put(reason, ruleTypes);
+ if (doc['event.outcome'].value == 'failure') {
+ String reason = doc['event.reason'].value;
+ String ruleType = doc['rule.category'].value;
+ Map ruleTypes = state.reasons.containsKey(reason) ? state.reasons.get(reason) : [:];
+ ruleTypes.put(ruleType, ruleTypes.containsKey(ruleType) ? ruleTypes.get(ruleType) + 1 : 1);
+ state.reasons.put(reason, ruleTypes);
}
`,
// Combine script is executed per cluster, but we already have a key-value pair per cluster.
@@ -168,7 +168,7 @@ export async function getTotalCountAggregations(
| 'count_rules_namespaces'
>
> {
- const { body: results } = await esClient.search({
+ const results = await esClient.search({
index: kibanaIndex,
body: {
size: 0,
@@ -182,13 +182,13 @@ export async function getTotalCountAggregations(
type: 'long',
script: {
source: `
- def alert = params._source['alert'];
- if (alert != null) {
- def actions = alert.actions;
- if (actions != null) {
- emit(actions.length);
- } else {
- emit(0);
+ def alert = params._source['alert'];
+ if (alert != null) {
+ def actions = alert.actions;
+ if (actions != null) {
+ emit(actions.length);
+ } else {
+ emit(0);
}
}`,
},
@@ -331,7 +331,7 @@ export async function getTotalCountAggregations(
}
export async function getTotalCountInUse(esClient: ElasticsearchClient, kibanaIndex: string) {
- const { body: searchResult } = await esClient.search({
+ const searchResult = await esClient.search({
index: kibanaIndex,
size: 0,
body: {
@@ -367,7 +367,7 @@ export async function getExecutionsPerDayCount(
esClient: ElasticsearchClient,
eventLogIndex: string
) {
- const { body: searchResult } = await esClient.search({
+ const searchResult = await esClient.search({
index: eventLogIndex,
size: 0,
body: {
@@ -489,7 +489,7 @@ export async function getExecutionTimeoutsPerDayCount(
esClient: ElasticsearchClient,
eventLogIndex: string
) {
- const { body: searchResult } = await esClient.search({
+ const searchResult = await esClient.search({
index: eventLogIndex,
size: 0,
body: {
@@ -544,7 +544,7 @@ export async function getFailedAndUnrecognizedTasksPerDay(
esClient: ElasticsearchClient,
taskManagerIndex: string
) {
- const { body: searchResult } = await esClient.search({
+ const searchResult = await esClient.search({
index: taskManagerIndex,
size: 0,
body: {
diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts
index bdbb1fe1dbcd3..310e9c30c71e0 100644
--- a/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts
+++ b/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts
@@ -76,14 +76,21 @@ export async function createApmTelemetry({
});
const search: CollectTelemetryParams['search'] = (params) =>
- unwrapEsResponse(esClient.asInternalUser.search(params)) as any;
+ unwrapEsResponse(
+ esClient.asInternalUser.search(params, { meta: true })
+ ) as any;
const indicesStats: CollectTelemetryParams['indicesStats'] = (params) =>
- unwrapEsResponse(esClient.asInternalUser.indices.stats(params));
+ unwrapEsResponse(
+ esClient.asInternalUser.indices.stats(params, { meta: true })
+ );
const transportRequest: CollectTelemetryParams['transportRequest'] = (
params
- ) => unwrapEsResponse(esClient.asInternalUser.transport.request(params));
+ ) =>
+ unwrapEsResponse(
+ esClient.asInternalUser.transport.request(params, { meta: true })
+ );
const dataTelemetry = await collectDataTelemetry({
search,
diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts
index 6e09e2aecfd48..ac801367662fc 100644
--- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts
@@ -118,7 +118,10 @@ export class APMEventClient {
const searchPromise = withApmSpan(operationName, () => {
const controller = new AbortController();
return cancelEsRequestOnAbort(
- this.esClient.search(searchParams, { signal: controller.signal }),
+ this.esClient.search(searchParams, {
+ signal: controller.signal,
+ meta: true,
+ }),
this.request,
controller
);
@@ -161,7 +164,7 @@ export class APMEventClient {
index: Array.isArray(index) ? index.join(',') : index,
...rest,
},
- { signal: controller.signal }
+ { signal: controller.signal, meta: true }
),
this.request,
controller
diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts
index 621f65f74d9f4..bd54c0916ef96 100644
--- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts
@@ -72,14 +72,14 @@ export function createInternalESClient({
): Promise> => {
return callEs(operationName, {
requestType: 'search',
- cb: (signal) => asInternalUser.search(params, { signal }),
+ cb: (signal) => asInternalUser.search(params, { signal, meta: true }),
params,
});
},
index: (operationName: string, params: APMIndexDocumentParams) => {
return callEs(operationName, {
requestType: 'index',
- cb: (signal) => asInternalUser.index(params, { signal }),
+ cb: (signal) => asInternalUser.index(params, { signal, meta: true }),
params,
});
},
@@ -89,7 +89,7 @@ export function createInternalESClient({
): Promise<{ result: string }> => {
return callEs(operationName, {
requestType: 'delete',
- cb: (signal) => asInternalUser.delete(params, { signal }),
+ cb: (signal) => asInternalUser.delete(params, { signal, meta: true }),
params,
});
},
@@ -99,7 +99,8 @@ export function createInternalESClient({
) => {
return callEs(operationName, {
requestType: 'indices.create',
- cb: (signal) => asInternalUser.indices.create(params, { signal }),
+ cb: (signal) =>
+ asInternalUser.indices.create(params, { signal, meta: true }),
params,
});
},
diff --git a/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts b/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts
index 9cde37d1d93f7..9e7eb1ea8c021 100644
--- a/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts
@@ -5,6 +5,7 @@
* 2.0.
*/
+import { elasticsearchServiceMock } from '../../../../../../src/core/server/mocks';
import { setupRequest } from './setup_request';
import { APMConfig } from '../..';
import { APMRouteHandlerResources } from '../../routes/typings';
@@ -32,14 +33,11 @@ jest.mock('../../routes/data_view/get_dynamic_data_view', () => ({
}));
function getMockResources() {
- const esClientMock = {
- asCurrentUser: {
- search: jest.fn().mockResolvedValue({ body: {} }),
- },
- asInternalUser: {
- search: jest.fn().mockResolvedValue({ body: {} }),
- },
- };
+ const esClientMock = elasticsearchServiceMock.createScopedClusterClient();
+ // @ts-expect-error incomplete definition
+ esClientMock.asCurrentUser.search.mockResponse({});
+ // @ts-expect-error incomplete definition
+ esClientMock.asInternalUser.search.mockResponse({});
const mockResources = {
config: new Proxy(
@@ -135,6 +133,7 @@ describe('setupRequest', () => {
},
{
signal: expect.any(Object),
+ meta: true,
}
);
});
@@ -157,6 +156,7 @@ describe('setupRequest', () => {
},
{
signal: expect.any(Object),
+ meta: true,
}
);
});
@@ -177,6 +177,7 @@ describe('setupRequest', () => {
const params =
mockResources.context.core.elasticsearch.client.asCurrentUser.search
.mock.calls[0][0];
+ // @ts-expect-error missing body definition
expect(params.body).toEqual({
query: {
bool: {
@@ -205,6 +206,7 @@ describe('setupRequest', () => {
const params =
mockResources.context.core.elasticsearch.client.asCurrentUser.search
.mock.calls[0][0];
+ // @ts-expect-error missing body definition
expect(params.body).toEqual({
query: {
bool: {
@@ -235,6 +237,7 @@ describe('without a bool filter', () => {
const params =
mockResources.context.core.elasticsearch.client.asCurrentUser.search.mock
.calls[0][0];
+ // @ts-expect-error missing body definition
expect(params.body).toEqual({
query: {
bool: {
@@ -266,6 +269,7 @@ describe('with includeFrozen=false', () => {
const params =
mockResources.context.core.elasticsearch.client.asCurrentUser.search.mock
.calls[0][0];
+ // @ts-expect-error missing body definition
expect(params.ignore_throttled).toBe(undefined);
});
});
@@ -286,6 +290,7 @@ describe('with includeFrozen=true', () => {
const params =
mockResources.context.core.elasticsearch.client.asCurrentUser.search.mock
.calls[0][0];
+ // @ts-expect-error missing body definition
expect(params.ignore_throttled).toBe(false);
});
});
diff --git a/x-pack/plugins/apm/server/routes/agent_keys/create_agent_key.ts b/x-pack/plugins/apm/server/routes/agent_keys/create_agent_key.ts
index d83a7af2737cd..3b47b81a86416 100644
--- a/x-pack/plugins/apm/server/routes/agent_keys/create_agent_key.ts
+++ b/x-pack/plugins/apm/server/routes/agent_keys/create_agent_key.ts
@@ -7,25 +7,9 @@
import Boom from '@hapi/boom';
import { ApmPluginRequestHandlerContext } from '../typings';
-import { CreateApiKeyResponse } from '../../../common/agent_key_types';
-import { PrivilegeType } from '../../../common/privilege_type';
const resource = '*';
-interface SecurityHasPrivilegesResponse {
- application: {
- apm: {
- [resource]: {
- [PrivilegeType.SOURCEMAP]: boolean;
- [PrivilegeType.EVENT]: boolean;
- [PrivilegeType.AGENT_CONFIG]: boolean;
- };
- };
- };
- has_all_requested: boolean;
- username: string;
-}
-
export async function createAgentKey({
context,
requestBody,
@@ -46,12 +30,10 @@ export async function createAgentKey({
// Elasticsearch will allow a user without the right apm privileges to create API keys, but the keys won't validate
// check first whether the user has the right privileges, and bail out early if not
const {
- body: {
- application: userApplicationPrivileges,
- username,
- has_all_requested: hasRequiredPrivileges,
- },
- } = await context.core.elasticsearch.client.asCurrentUser.security.hasPrivileges(
+ application: userApplicationPrivileges,
+ username,
+ has_all_requested: hasRequiredPrivileges,
+ } = await context.core.elasticsearch.client.asCurrentUser.security.hasPrivileges(
{
body: {
application: [application],
@@ -97,8 +79,8 @@ export async function createAgentKey({
},
};
- const { body: agentKey } =
- await context.core.elasticsearch.client.asCurrentUser.security.createApiKey(
+ const agentKey =
+ await context.core.elasticsearch.client.asCurrentUser.security.createApiKey(
{
body,
}
diff --git a/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys.ts b/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys.ts
index 9c5b3e04c94f2..dff7b3b5c32ab 100644
--- a/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys.ts
+++ b/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys.ts
@@ -36,7 +36,7 @@ export async function getAgentKeys({
body,
});
- const agentKeys = apiResponse.body.api_keys.filter(
+ const agentKeys = apiResponse.api_keys.filter(
({ invalidated }) => !invalidated
);
return {
diff --git a/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts b/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts
index 4aed9314f433c..29514739f2225 100644
--- a/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts
+++ b/x-pack/plugins/apm/server/routes/agent_keys/get_agent_keys_privileges.ts
@@ -8,14 +8,6 @@
import { ApmPluginRequestHandlerContext } from '../typings';
import { APMPluginStartDependencies } from '../../types';
-interface SecurityHasPrivilegesResponse {
- cluster: {
- manage_security: boolean;
- manage_api_key: boolean;
- manage_own_api_key: boolean;
- };
-}
-
export async function getAgentKeysPrivileges({
context,
securityPluginStart,
@@ -24,23 +16,19 @@ export async function getAgentKeysPrivileges({
securityPluginStart: NonNullable;
}) {
const [securityHasPrivilegesResponse, areApiKeysEnabled] = await Promise.all([
- context.core.elasticsearch.client.asCurrentUser.security.hasPrivileges(
- {
- body: {
- cluster: ['manage_security', 'manage_api_key', 'manage_own_api_key'],
- },
- }
- ),
+ context.core.elasticsearch.client.asCurrentUser.security.hasPrivileges({
+ body: {
+ cluster: ['manage_security', 'manage_api_key', 'manage_own_api_key'],
+ },
+ }),
securityPluginStart.authc.apiKeys.areAPIKeysEnabled(),
]);
const {
- body: {
- cluster: {
- manage_security: manageSecurity,
- manage_api_key: manageApiKey,
- manage_own_api_key: manageOwnApiKey,
- },
+ cluster: {
+ manage_security: manageSecurity,
+ manage_api_key: manageApiKey,
+ manage_own_api_key: manageOwnApiKey,
},
} = securityHasPrivilegesResponse;
diff --git a/x-pack/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts b/x-pack/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts
index 1ccb63382de4e..99c5008718403 100644
--- a/x-pack/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts
+++ b/x-pack/plugins/apm/server/routes/agent_keys/invalidate_agent_key.ts
@@ -13,16 +13,15 @@ export async function invalidateAgentKey({
context: ApmPluginRequestHandlerContext;
id: string;
}) {
- const {
- body: { invalidated_api_keys: invalidatedAgentKeys },
- } = await context.core.elasticsearch.client.asCurrentUser.security.invalidateApiKey(
- {
- body: {
- ids: [id],
- owner: true,
- },
- }
- );
+ const { invalidated_api_keys: invalidatedAgentKeys } =
+ await context.core.elasticsearch.client.asCurrentUser.security.invalidateApiKey(
+ {
+ body: {
+ ids: [id],
+ owner: true,
+ },
+ }
+ );
return {
invalidatedAgentKeys,
diff --git a/x-pack/plugins/apm/server/routes/alerts/alerting_es_client.ts b/x-pack/plugins/apm/server/routes/alerts/alerting_es_client.ts
index 9445a0f0610f6..876d02137c3f8 100644
--- a/x-pack/plugins/apm/server/routes/alerts/alerting_es_client.ts
+++ b/x-pack/plugins/apm/server/routes/alerts/alerting_es_client.ts
@@ -27,5 +27,5 @@ export async function alertingEsClient({
ignore_unavailable: true,
});
- return response.body as unknown as ESSearchResponse;
+ return response as unknown as ESSearchResponse;
}
diff --git a/x-pack/plugins/apm/server/routes/alerts/register_error_count_alert_type.test.ts b/x-pack/plugins/apm/server/routes/alerts/register_error_count_alert_type.test.ts
index 01aa64b85f720..e1e807c05400c 100644
--- a/x-pack/plugins/apm/server/routes/alerts/register_error_count_alert_type.test.ts
+++ b/x-pack/plugins/apm/server/routes/alerts/register_error_count_alert_type.test.ts
@@ -6,8 +6,6 @@
*/
import { registerErrorCountAlertType } from './register_error_count_alert_type';
-// eslint-disable-next-line @kbn/eslint/no-restricted-paths
-import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks';
import { createRuleTypeMocks } from './test_utils';
describe('Error count alert', () => {
@@ -18,25 +16,23 @@ describe('Error count alert', () => {
const params = { threshold: 1 };
- services.scopedClusterClient.asCurrentUser.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- hits: {
- hits: [],
- total: {
- relation: 'eq',
- value: 0,
- },
+ services.scopedClusterClient.asCurrentUser.search.mockResponse({
+ hits: {
+ hits: [],
+ total: {
+ relation: 'eq',
+ value: 0,
},
- took: 0,
- timed_out: false,
- _shards: {
- failed: 0,
- skipped: 0,
- successful: 1,
- total: 1,
- },
- })
- );
+ },
+ took: 0,
+ timed_out: false,
+ _shards: {
+ failed: 0,
+ skipped: 0,
+ successful: 1,
+ total: 1,
+ },
+ });
await executor({ params });
expect(services.alertFactory.create).not.toBeCalled();
@@ -50,87 +46,85 @@ describe('Error count alert', () => {
const params = { threshold: 2, windowSize: 5, windowUnit: 'm' };
- services.scopedClusterClient.asCurrentUser.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- hits: {
- hits: [],
- total: {
- relation: 'eq',
- value: 2,
- },
+ services.scopedClusterClient.asCurrentUser.search.mockResponse({
+ hits: {
+ hits: [],
+ total: {
+ relation: 'eq',
+ value: 2,
},
- aggregations: {
- error_counts: {
- buckets: [
- {
- key: ['foo', 'env-foo'],
- doc_count: 5,
- latest: {
- top: [
- {
- metrics: {
- 'service.name': 'foo',
- 'service.environment': 'env-foo',
- },
+ },
+ aggregations: {
+ error_counts: {
+ buckets: [
+ {
+ key: ['foo', 'env-foo'],
+ doc_count: 5,
+ latest: {
+ top: [
+ {
+ metrics: {
+ 'service.name': 'foo',
+ 'service.environment': 'env-foo',
},
- ],
- },
+ },
+ ],
},
- {
- key: ['foo', 'env-foo-2'],
- doc_count: 4,
- latest: {
- top: [
- {
- metrics: {
- 'service.name': 'foo',
- 'service.environment': 'env-foo-2',
- },
+ },
+ {
+ key: ['foo', 'env-foo-2'],
+ doc_count: 4,
+ latest: {
+ top: [
+ {
+ metrics: {
+ 'service.name': 'foo',
+ 'service.environment': 'env-foo-2',
},
- ],
- },
+ },
+ ],
},
- {
- key: ['bar', 'env-bar'],
- doc_count: 3,
- latest: {
- top: [
- {
- metrics: {
- 'service.name': 'bar',
- 'service.environment': 'env-bar',
- },
+ },
+ {
+ key: ['bar', 'env-bar'],
+ doc_count: 3,
+ latest: {
+ top: [
+ {
+ metrics: {
+ 'service.name': 'bar',
+ 'service.environment': 'env-bar',
},
- ],
- },
+ },
+ ],
},
- {
- key: ['bar', 'env-bar-2'],
- doc_count: 1,
- latest: {
- top: [
- {
- metrics: {
- 'service.name': 'bar',
- 'service.environment': 'env-bar-2',
- },
+ },
+ {
+ key: ['bar', 'env-bar-2'],
+ doc_count: 1,
+ latest: {
+ top: [
+ {
+ metrics: {
+ 'service.name': 'bar',
+ 'service.environment': 'env-bar-2',
},
- ],
- },
+ },
+ ],
},
- ],
- },
+ },
+ ],
},
- took: 0,
- timed_out: false,
- _shards: {
- failed: 0,
- skipped: 0,
- successful: 1,
- total: 1,
- },
- })
- );
+ },
+ took: 0,
+ timed_out: false,
+ _shards: {
+ failed: 0,
+ skipped: 0,
+ successful: 1,
+ total: 1,
+ },
+ });
await executor({ params });
[
diff --git a/x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_alert_type.test.ts b/x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_alert_type.test.ts
index 956347098d787..debe14e41db11 100644
--- a/x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_alert_type.test.ts
+++ b/x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_alert_type.test.ts
@@ -7,8 +7,6 @@
import { registerTransactionDurationAlertType } from './register_transaction_duration_alert_type';
import { createRuleTypeMocks } from './test_utils';
-// eslint-disable-next-line @kbn/eslint/no-restricted-paths
-import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks';
describe('registerTransactionDurationAlertType', () => {
it('sends alert when value is greater than threashold', async () => {
@@ -17,30 +15,28 @@ describe('registerTransactionDurationAlertType', () => {
registerTransactionDurationAlertType(dependencies);
- services.scopedClusterClient.asCurrentUser.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- hits: {
- hits: [],
- total: {
- relation: 'eq',
- value: 2,
- },
+ services.scopedClusterClient.asCurrentUser.search.mockResponse({
+ hits: {
+ hits: [],
+ total: {
+ relation: 'eq',
+ value: 2,
},
- aggregations: {
- latency: {
- value: 5500000,
- },
+ },
+ aggregations: {
+ latency: {
+ value: 5500000,
},
- took: 0,
- timed_out: false,
- _shards: {
- failed: 0,
- skipped: 0,
- successful: 1,
- total: 1,
- },
- })
- );
+ },
+ took: 0,
+ timed_out: false,
+ _shards: {
+ failed: 0,
+ skipped: 0,
+ successful: 1,
+ total: 1,
+ },
+ });
const params = {
threshold: 3000,
diff --git a/x-pack/plugins/apm/server/routes/alerts/register_transaction_error_rate_alert_type.test.ts b/x-pack/plugins/apm/server/routes/alerts/register_transaction_error_rate_alert_type.test.ts
index 64540e144d8a8..a054dcba53a3b 100644
--- a/x-pack/plugins/apm/server/routes/alerts/register_transaction_error_rate_alert_type.test.ts
+++ b/x-pack/plugins/apm/server/routes/alerts/register_transaction_error_rate_alert_type.test.ts
@@ -6,8 +6,6 @@
*/
import { registerTransactionErrorRateAlertType } from './register_transaction_error_rate_alert_type';
-// eslint-disable-next-line @kbn/eslint/no-restricted-paths
-import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks';
import { createRuleTypeMocks } from './test_utils';
describe('Transaction error rate alert', () => {
@@ -20,30 +18,28 @@ describe('Transaction error rate alert', () => {
const params = { threshold: 1 };
- services.scopedClusterClient.asCurrentUser.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- hits: {
- hits: [],
- total: {
- relation: 'eq',
- value: 0,
- },
+ services.scopedClusterClient.asCurrentUser.search.mockResponse({
+ hits: {
+ hits: [],
+ total: {
+ relation: 'eq',
+ value: 0,
},
- took: 0,
- timed_out: false,
- aggregations: {
- series: {
- buckets: [],
- },
+ },
+ took: 0,
+ timed_out: false,
+ aggregations: {
+ series: {
+ buckets: [],
},
- _shards: {
- failed: 0,
- skipped: 0,
- successful: 1,
- total: 1,
- },
- })
- );
+ },
+ _shards: {
+ failed: 0,
+ skipped: 0,
+ successful: 1,
+ total: 1,
+ },
+ });
await executor({ params });
expect(services.alertFactory.create).not.toBeCalled();
@@ -57,61 +53,59 @@ describe('Transaction error rate alert', () => {
...dependencies,
});
- services.scopedClusterClient.asCurrentUser.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- hits: {
- hits: [],
- total: {
- relation: 'eq',
- value: 0,
- },
+ services.scopedClusterClient.asCurrentUser.search.mockResponse({
+ hits: {
+ hits: [],
+ total: {
+ relation: 'eq',
+ value: 0,
},
- aggregations: {
- series: {
- buckets: [
- {
- key: ['foo', 'env-foo', 'type-foo'],
- outcomes: {
- buckets: [
- {
- key: 'success',
- doc_count: 90,
- },
- {
- key: 'failure',
- doc_count: 10,
- },
- ],
- },
+ },
+ aggregations: {
+ series: {
+ buckets: [
+ {
+ key: ['foo', 'env-foo', 'type-foo'],
+ outcomes: {
+ buckets: [
+ {
+ key: 'success',
+ doc_count: 90,
+ },
+ {
+ key: 'failure',
+ doc_count: 10,
+ },
+ ],
},
- {
- key: ['bar', 'env-bar', 'type-bar'],
- outcomes: {
- buckets: [
- {
- key: 'success',
- doc_count: 90,
- },
- {
- key: 'failure',
- doc_count: 1,
- },
- ],
- },
+ },
+ {
+ key: ['bar', 'env-bar', 'type-bar'],
+ outcomes: {
+ buckets: [
+ {
+ key: 'success',
+ doc_count: 90,
+ },
+ {
+ key: 'failure',
+ doc_count: 1,
+ },
+ ],
},
- ],
- },
+ },
+ ],
},
- took: 0,
- timed_out: false,
- _shards: {
- failed: 0,
- skipped: 0,
- successful: 1,
- total: 1,
- },
- })
- );
+ },
+ took: 0,
+ timed_out: false,
+ _shards: {
+ failed: 0,
+ skipped: 0,
+ successful: 1,
+ total: 1,
+ },
+ });
const params = { threshold: 10, windowSize: 5, windowUnit: 'm' };
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_boolean_field_stats.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_boolean_field_stats.ts
index 9fe1c1f882f1d..13910ef7104fb 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_boolean_field_stats.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_boolean_field_stats.ts
@@ -72,7 +72,7 @@ export const fetchBooleanFieldStats = async (
field.fieldName,
termFilters
);
- const { body } = await esClient.search(request);
+ const body = await esClient.search(request);
const aggregations = body.aggregations;
const stats: BooleanFieldStats = {
fieldName: field.fieldName,
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_field_stats.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_field_stats.test.ts
index 30bebc4c24774..1c979bc3e4c6d 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_field_stats.test.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_field_stats.test.ts
@@ -99,31 +99,23 @@ describe('field_stats', () => {
describe('fetchFieldsStats', () => {
it('returns field candidates and total hits', async () => {
const fieldsCaps = {
- body: {
- fields: {
- myIpFieldName: { ip: {} },
- myKeywordFieldName: { keyword: {} },
- myMultiFieldName: { keyword: {}, text: {} },
- myHistogramFieldName: { histogram: {} },
- myNumericFieldName: { number: {} },
- },
+ fields: {
+ myIpFieldName: { ip: {} },
+ myKeywordFieldName: { keyword: {} },
+ myMultiFieldName: { keyword: {}, text: {} },
+ myHistogramFieldName: { histogram: {} },
+ myNumericFieldName: { number: {} },
},
};
const esClientFieldCapsMock = jest.fn(() => fieldsCaps);
- const fieldsToSample = Object.keys(fieldsCaps.body.fields);
+ const fieldsToSample = Object.keys(fieldsCaps.fields);
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
+ (req: estypes.SearchRequest): estypes.SearchResponse => {
return {
- body: {
- aggregations: { sample: {} },
- } as unknown as estypes.SearchResponse,
- };
+ aggregations: { sample: {} },
+ } as unknown as estypes.SearchResponse;
}
);
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_field_value_stats.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_field_value_stats.ts
index 709e2ad4a99fd..c500d1d49dd6e 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_field_value_stats.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_field_value_stats.ts
@@ -55,7 +55,7 @@ export const fetchFieldValueFieldStats = async (
): Promise => {
const request = getFieldValueFieldStatsRequest(params, field);
- const { body } = await esClient.search(request);
+ const body = await esClient.search(request);
const aggregations = body.aggregations as {
filtered_count: estypes.AggregationsSingleBucketAggregateBase;
};
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_fields_stats.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_fields_stats.ts
index 513252ee65e11..e44996337f4b1 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_fields_stats.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_fields_stats.ts
@@ -34,7 +34,7 @@ export const fetchFieldsStats = async (
fields: fieldsToSample,
});
- const fieldStatsPromises = Object.entries(respMapping.body.fields)
+ const fieldStatsPromises = Object.entries(respMapping.fields)
.map(([key, value], idx) => {
const field: FieldValuePair = { fieldName: key, fieldValue: '' };
const fieldTypes = Object.keys(value);
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_keyword_field_stats.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_keyword_field_stats.ts
index 55ead5230e951..35b8eab5712ec 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_keyword_field_stats.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_keyword_field_stats.ts
@@ -52,6 +52,7 @@ interface SampledTopAggs
extends estypes.AggregationsTermsAggregateBase {
buckets: TopValueBucket[];
}
+
export const fetchKeywordFieldStats = async (
esClient: ElasticsearchClient,
params: FieldStatsCommonRequestParams,
@@ -63,10 +64,9 @@ export const fetchKeywordFieldStats = async (
field.fieldName,
termFilters
);
- const { body } = await esClient.search<
- unknown,
- { sampled_top: SampledTopAggs }
- >(request);
+ const body = await esClient.search(
+ request
+ );
const aggregations = body.aggregations;
const topValues = aggregations?.sampled_top?.buckets ?? [];
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_numeric_field_stats.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_numeric_field_stats.ts
index 2adb4502e4043..192377b88a992 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_numeric_field_stats.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_numeric_field_stats.ts
@@ -82,7 +82,7 @@ export const fetchNumericFieldStats = async (
field.fieldName,
termFilters
);
- const { body } = await esClient.search(request);
+ const body = await esClient.search(request);
const aggregations = body.aggregations;
const docCount = aggregations?.sampled_field_stats?.doc_count ?? 0;
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.test.ts
index 6cbf97a163871..8f5029c7a3e9e 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.test.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.test.ts
@@ -72,24 +72,18 @@ describe('query_correlation', () => {
const KsTestLess = 0.01;
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
+ (req: estypes.SearchRequest): estypes.SearchResponse => {
return {
- body: {
- aggregations: {
- latency_ranges: {
- buckets: latencyRangesBuckets,
- },
- transaction_duration_correlation: {
- value: transactionDurationCorrelationValue,
- },
- ks_test: { less: KsTestLess },
+ aggregations: {
+ latency_ranges: {
+ buckets: latencyRangesBuckets,
+ },
+ transaction_duration_correlation: {
+ value: transactionDurationCorrelationValue,
},
- } as unknown as estypes.SearchResponse,
- };
+ ks_test: { less: KsTestLess },
+ },
+ } as unknown as estypes.SearchResponse;
}
);
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.ts
index caf1386fbf025..c859853f6896b 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.ts
@@ -123,16 +123,16 @@ export const fetchTransactionDurationCorrelation = async (
)
);
- if (resp.body.aggregations === undefined) {
+ if (resp.aggregations === undefined) {
throw new Error(
'fetchTransactionDurationCorrelation failed, did not return aggregations.'
);
}
const result = {
- ranges: resp.body.aggregations.latency_ranges.buckets,
- correlation: resp.body.aggregations.transaction_duration_correlation.value,
- ksTest: resp.body.aggregations.ks_test.less,
+ ranges: resp.aggregations.latency_ranges.buckets,
+ correlation: resp.aggregations.transaction_duration_correlation.value,
+ ksTest: resp.aggregations.ks_test.less,
};
return result;
};
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation_with_histogram.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation_with_histogram.test.ts
index 2e1a635671794..10994c6c017e0 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation_with_histogram.test.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation_with_histogram.test.ts
@@ -38,14 +38,8 @@ describe('query_correlation_with_histogram', () => {
describe('fetchTransactionDurationCorrelationWithHistogram', () => {
it(`doesn't break on failing ES queries and adds messages to the log`, async () => {
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
- return {
- body: {} as unknown as estypes.SearchResponse,
- };
+ (req: estypes.SearchRequest): Promise => {
+ return Promise.resolve({} as unknown as estypes.SearchResponse);
}
);
@@ -81,21 +75,15 @@ describe('query_correlation_with_histogram', () => {
it('returns items with correlation and ks-test value', async () => {
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
- return {
- body: {
- aggregations: {
- latency_ranges: { buckets: [] },
- transaction_duration_correlation: { value: 0.6 },
- ks_test: { less: 0.001 },
- logspace_ranges: { buckets: [] },
- },
- } as unknown as estypes.SearchResponse,
- };
+ (req: estypes.SearchRequest): Promise => {
+ return Promise.resolve({
+ aggregations: {
+ latency_ranges: { buckets: [] },
+ transaction_duration_correlation: { value: 0.6 },
+ ks_test: { less: 0.001 },
+ logspace_ranges: { buckets: [] },
+ },
+ } as unknown as estypes.SearchResponse);
}
);
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_failure_correlation.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_failure_correlation.ts
index f50a610aeac71..46a980a53ab48 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_failure_correlation.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_failure_correlation.ts
@@ -80,13 +80,13 @@ export const fetchFailedTransactionsCorrelationPValues = async (
getFailureCorrelationRequest(params, fieldName)
);
- if (resp.body.aggregations === undefined) {
+ if (resp.aggregations === undefined) {
throw new Error(
'fetchErrorCorrelation failed, did not return aggregations.'
);
}
- const overallResult = resp.body.aggregations.failure_p_value;
+ const overallResult = resp.aggregations.failure_p_value;
// Using for of to sequentially augment the results with histogram data.
const result: FailedTransactionsCorrelation[] = [];
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.test.ts
index 957e2393558ed..0ecbd6477fda7 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.test.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.test.ts
@@ -97,36 +97,28 @@ describe('query_field_candidates', () => {
describe('fetchTransactionDurationFieldCandidates', () => {
it('returns field candidates and total hits', async () => {
const esClientFieldCapsMock = jest.fn(() => ({
- body: {
- fields: {
- myIpFieldName: { ip: {} },
- myKeywordFieldName: { keyword: {} },
- myUnpopulatedKeywordFieldName: { keyword: {} },
- myNumericFieldName: { number: {} },
- },
+ fields: {
+ myIpFieldName: { ip: {} },
+ myKeywordFieldName: { keyword: {} },
+ myUnpopulatedKeywordFieldName: { keyword: {} },
+ myNumericFieldName: { number: {} },
},
}));
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
+ (req: estypes.SearchRequest): estypes.SearchResponse => {
return {
- body: {
- hits: {
- hits: [
- {
- fields: {
- myIpFieldName: '1.1.1.1',
- myKeywordFieldName: 'myKeywordFieldValue',
- myNumericFieldName: 1234,
- },
+ hits: {
+ hits: [
+ {
+ fields: {
+ myIpFieldName: '1.1.1.1',
+ myKeywordFieldName: 'myKeywordFieldValue',
+ myNumericFieldName: 1234,
},
- ],
- },
- } as unknown as estypes.SearchResponse,
- };
+ },
+ ],
+ },
+ } as unknown as estypes.SearchResponse;
}
);
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.ts
index 801bb18e8957a..2d6347362e8ea 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.ts
@@ -70,7 +70,7 @@ export const fetchTransactionDurationFieldCandidates = async (
const finalFieldCandidates = new Set(FIELDS_TO_ADD_AS_CANDIDATE);
const acceptableFields: Set = new Set();
- Object.entries(respMapping.body.fields).forEach(([key, value]) => {
+ Object.entries(respMapping.fields).forEach(([key, value]) => {
const fieldTypes = Object.keys(value) as ES_FIELD_TYPES[];
const isSupportedType = fieldTypes.some((type) =>
SUPPORTED_ES_FIELD_TYPES.includes(type)
@@ -87,7 +87,7 @@ export const fetchTransactionDurationFieldCandidates = async (
});
const resp = await esClient.search(getRandomDocsRequest(params));
- const sampledDocs = resp.body.hits.hits.map((d) => d.fields ?? {});
+ const sampledDocs = resp.hits.hits.map((d) => d.fields ?? {});
// Get all field names for each returned doc and flatten it
// to a list of unique field names used across all docs
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.test.ts
index 80016930184b3..4f7c44e5f3107 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.test.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.test.ts
@@ -42,20 +42,14 @@ describe('query_field_value_pairs', () => {
];
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
+ (req: estypes.SearchRequest): estypes.SearchResponse => {
return {
- body: {
- aggregations: {
- attribute_terms: {
- buckets: [{ key: 'myValue1' }, { key: 'myValue2' }],
- },
+ aggregations: {
+ attribute_terms: {
+ buckets: [{ key: 'myValue1' }, { key: 'myValue2' }],
},
- } as unknown as estypes.SearchResponse,
- };
+ },
+ } as unknown as estypes.SearchResponse;
}
);
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.ts
index ac31985ecd190..6bcec359c157a 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.ts
@@ -55,13 +55,13 @@ const fetchTransactionDurationFieldTerms = async (
getTermsAggRequest(params, fieldName)
);
- if (resp.body.aggregations === undefined) {
+ if (resp.aggregations === undefined) {
throw new Error(
'fetchTransactionDurationFieldTerms failed, did not return aggregations.'
);
}
- const buckets = resp.body.aggregations.attribute_terms?.buckets;
+ const buckets = resp.aggregations.attribute_terms?.buckets;
if (buckets?.length >= 1) {
return buckets.map((d) => ({
fieldName,
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.test.ts
index 12b054e18bab7..d8fada32cb74c 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.test.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.test.ts
@@ -40,21 +40,15 @@ describe('query_fractions', () => {
describe('fetchTransactionDurationFractions', () => {
it('computes the actual percentile bucket counts and actual fractions', async () => {
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
+ (req: estypes.SearchRequest): estypes.SearchResponse => {
return {
- body: {
- hits: { total: { value: 3 } },
- aggregations: {
- latency_ranges: {
- buckets: [{ doc_count: 1 }, { doc_count: 2 }],
- },
+ hits: { total: { value: 3 } },
+ aggregations: {
+ latency_ranges: {
+ buckets: [{ doc_count: 1 }, { doc_count: 2 }],
},
- } as unknown as estypes.SearchResponse,
- };
+ },
+ } as unknown as estypes.SearchResponse;
}
);
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.ts
index a4e9e0c13fa59..867a4defcb01b 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.ts
@@ -52,20 +52,20 @@ export const fetchTransactionDurationFractions = async (
getTransactionDurationRangesRequest(params, ranges)
);
- if ((resp.body.hits.total as estypes.SearchTotalHits).value === 0) {
+ if ((resp.hits.total as estypes.SearchTotalHits).value === 0) {
return {
fractions: [],
totalDocCount: 0,
};
}
- if (resp.body.aggregations === undefined) {
+ if (resp.aggregations === undefined) {
throw new Error(
'fetchTransactionDurationFractions failed, did not return aggregations.'
);
}
- const buckets = resp.body.aggregations.latency_ranges?.buckets;
+ const buckets = resp.aggregations.latency_ranges?.buckets;
const totalDocCount = buckets.reduce((acc, bucket) => {
return acc + bucket.doc_count;
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.test.ts
index c9ea70452bdb0..7b60d93d0b745 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.test.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.test.ts
@@ -79,20 +79,14 @@ describe('query_histogram', () => {
];
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
+ (req: estypes.SearchRequest): estypes.SearchResponse => {
return {
- body: {
- aggregations: {
- transaction_duration_histogram: {
- buckets: histogramBucket,
- },
+ aggregations: {
+ transaction_duration_histogram: {
+ buckets: histogramBucket,
},
- } as unknown as estypes.SearchResponse,
- };
+ },
+ } as unknown as estypes.SearchResponse;
}
);
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.ts
index 5f32e1ef7cf5b..943718c986a7a 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.ts
@@ -52,11 +52,11 @@ export const fetchTransactionDurationHistogram = async (
{ transaction_duration_histogram: Aggs }
>(getTransactionDurationHistogramRequest(params, interval, termFilters));
- if (resp.body.aggregations === undefined) {
+ if (resp.aggregations === undefined) {
throw new Error(
'fetchTransactionDurationHistogram failed, did not return aggregations.'
);
}
- return resp.body.aggregations.transaction_duration_histogram.buckets ?? [];
+ return resp.aggregations.transaction_duration_histogram.buckets ?? [];
};
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.test.ts
index 526207beaabce..891c2af077e63 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.test.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.test.ts
@@ -75,24 +75,18 @@ describe('query_histogram_range_steps', () => {
describe('fetchTransactionDurationHistogramRangeSteps', () => {
it('fetches the range steps for the log histogram', async () => {
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
+ (req: estypes.SearchRequest): estypes.SearchResponse => {
return {
- body: {
- hits: { total: { value: 10 } },
- aggregations: {
- transaction_duration_max: {
- value: 10000,
- },
- transaction_duration_min: {
- value: 10,
- },
+ hits: { total: { value: 10 } },
+ aggregations: {
+ transaction_duration_max: {
+ value: 10000,
},
- } as unknown as estypes.SearchResponse,
- };
+ transaction_duration_min: {
+ value: 10,
+ },
+ },
+ } as unknown as estypes.SearchResponse;
}
);
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.ts
index 159b5379df194..d260a22fb6e84 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.ts
@@ -61,18 +61,18 @@ export const fetchTransactionDurationHistogramRangeSteps = async (
}
>(getHistogramIntervalRequest(params));
- if ((resp.body.hits.total as estypes.SearchTotalHits).value === 0) {
+ if ((resp.hits.total as estypes.SearchTotalHits).value === 0) {
return getHistogramRangeSteps(0, 1, 100);
}
- if (resp.body.aggregations === undefined) {
+ if (resp.aggregations === undefined) {
throw new Error(
'fetchTransactionDurationHistogramRangeSteps failed, did not return aggregations.'
);
}
- const min = resp.body.aggregations.transaction_duration_min.value;
- const max = resp.body.aggregations.transaction_duration_max.value * 2;
+ const min = resp.aggregations.transaction_duration_min.value;
+ const max = resp.aggregations.transaction_duration_max.value * 2;
return getHistogramRangeSteps(min, max, steps);
};
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.test.ts
index 4e637d1ca6f4a..876225179aaa7 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.test.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.test.ts
@@ -85,24 +85,17 @@ describe('query_percentiles', () => {
};
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
+ (req: estypes.SearchRequest): estypes.SearchResponse => {
return {
- body: {
- hits: { total: { value: totalDocs } },
- aggregations: {
- transaction_duration_percentiles: {
- values: percentilesValues,
- },
+ hits: { total: { value: totalDocs } },
+ aggregations: {
+ transaction_duration_percentiles: {
+ values: percentilesValues,
},
- } as unknown as estypes.SearchResponse,
- };
+ },
+ } as unknown as estypes.SearchResponse;
}
);
-
const esClientMock = {
search: esClientSearchMock,
} as unknown as ElasticsearchClient;
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.ts
index c5d2e8a5af7fd..e7ecb03fa342e 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.ts
@@ -64,19 +64,19 @@ export const fetchTransactionDurationPercentiles = async (
>(getTransactionDurationPercentilesRequest(params, percents, termFilters));
// return early with no results if the search didn't return any documents
- if ((resp.body.hits.total as estypes.SearchTotalHits).value === 0) {
+ if ((resp.hits.total as estypes.SearchTotalHits).value === 0) {
return { totalDocs: 0, percentiles: {} };
}
- if (resp.body.aggregations === undefined) {
+ if (resp.aggregations === undefined) {
throw new Error(
'fetchTransactionDurationPercentiles failed, did not return aggregations.'
);
}
return {
- totalDocs: (resp.body.hits.total as estypes.SearchTotalHits).value,
+ totalDocs: (resp.hits.total as estypes.SearchTotalHits).value,
percentiles:
- resp.body.aggregations.transaction_duration_percentiles.values ?? {},
+ resp.aggregations.transaction_duration_percentiles.values ?? {},
};
};
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.test.ts
index 5c43b771f69ee..2b233958ce273 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.test.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.test.ts
@@ -110,20 +110,14 @@ describe('query_ranges', () => {
];
const esClientSearchMock = jest.fn(
- (
- req: estypes.SearchRequest
- ): {
- body: estypes.SearchResponse;
- } => {
+ (req: estypes.SearchRequest): estypes.SearchResponse => {
return {
- body: {
- aggregations: {
- logspace_ranges: {
- buckets: logspaceRangesBuckets,
- },
+ aggregations: {
+ logspace_ranges: {
+ buckets: logspaceRangesBuckets,
},
- } as unknown as estypes.SearchResponse,
- };
+ },
+ } as unknown as estypes.SearchResponse;
}
);
diff --git a/x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.ts
index 1440e9a1576d9..b2b591519dc9c 100644
--- a/x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.ts
+++ b/x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.ts
@@ -72,13 +72,13 @@ export const fetchTransactionDurationRanges = async (
getTransactionDurationRangesRequest(params, rangesSteps, termFilters)
);
- if (resp.body.aggregations === undefined) {
+ if (resp.aggregations === undefined) {
throw new Error(
'fetchTransactionDurationCorrelation failed, did not return aggregations.'
);
}
- return resp.body.aggregations.logspace_ranges.buckets
+ return resp.aggregations.logspace_ranges.buckets
.map((d) => ({
key: d.from,
doc_count: d.doc_count,
diff --git a/x-pack/plugins/apm/server/routes/services/annotations/get_stored_annotations.ts b/x-pack/plugins/apm/server/routes/services/annotations/get_stored_annotations.ts
index 308a1b9a2db26..7ce9eddf65981 100644
--- a/x-pack/plugins/apm/server/routes/services/annotations/get_stored_annotations.ts
+++ b/x-pack/plugins/apm/server/routes/services/annotations/get_stored_annotations.ts
@@ -56,10 +56,13 @@ export function getStoredAnnotations({
try {
const response: ESSearchResponse =
(await unwrapEsResponse(
- client.search({
- index: annotationsClient.index,
- body,
- })
+ client.search(
+ {
+ index: annotationsClient.index,
+ body,
+ },
+ { meta: true }
+ )
)) as any;
return response.hits.hits.map((hit) => {
diff --git a/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts b/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts
index b0e219a4d886d..bd855c93ed507 100644
--- a/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts
+++ b/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts
@@ -152,7 +152,7 @@ const customElementCollector: TelemetryCollector = async function customElementC
body: { query: { bool: { filter: { term: { type: CUSTOM_ELEMENT_TYPE } } } } },
};
- const { body: esResponse } = await esClient.search(customElementParams);
+ const esResponse = await esClient.search(customElementParams);
if (get(esResponse, 'hits.hits.length') > 0) {
const customElements = esResponse.hits.hits.map((hit) => hit._source![CUSTOM_ELEMENT_TYPE]);
diff --git a/x-pack/plugins/canvas/server/collectors/workpad_collector.ts b/x-pack/plugins/canvas/server/collectors/workpad_collector.ts
index 62b0ce200e320..b47ea33a24f4c 100644
--- a/x-pack/plugins/canvas/server/collectors/workpad_collector.ts
+++ b/x-pack/plugins/canvas/server/collectors/workpad_collector.ts
@@ -386,7 +386,7 @@ const workpadCollector: TelemetryCollector = async function (kibanaIndex, esClie
body: { query: { bool: { filter: { term: { type: CANVAS_TYPE } } } } },
};
- const { body: esResponse } = await esClient.search(searchParams);
+ const esResponse = await esClient.search(searchParams);
if (get(esResponse, 'hits.hits.length') > 0) {
const workpads = esResponse.hits.hits.map((hit) => hit._source![CANVAS_TYPE]);
diff --git a/x-pack/plugins/canvas/server/lib/essql_strategy.ts b/x-pack/plugins/canvas/server/lib/essql_strategy.ts
index 273ffb53b0ed2..0cc5c8a21121b 100644
--- a/x-pack/plugins/canvas/server/lib/essql_strategy.ts
+++ b/x-pack/plugins/canvas/server/lib/essql_strategy.ts
@@ -27,23 +27,26 @@ export const essqlSearchStrategyProvider = (): ISearchStrategy<
const searchUntilEnd = async () => {
try {
- let response = await esClient.asCurrentUser.sql.query({
- format: 'json',
- body: {
- query,
- // @ts-expect-error `params` missing from `QuerySqlRequest` type
- params,
- field_multi_value_leniency: true,
- time_zone: timezone,
- fetch_size: count,
- client_id: 'canvas',
- filter: {
- bool: {
- must: [{ match_all: {} }, ...buildBoolArray(filter)],
+ let response = await esClient.asCurrentUser.sql.query(
+ {
+ format: 'json',
+ body: {
+ query,
+ // @ts-expect-error `params` missing from `QuerySqlRequest` type
+ params,
+ field_multi_value_leniency: true,
+ time_zone: timezone,
+ fetch_size: count,
+ client_id: 'canvas',
+ filter: {
+ bool: {
+ must: [{ match_all: {} }, ...buildBoolArray(filter)],
+ },
},
},
},
- });
+ { meta: true }
+ );
let body = response.body;
@@ -60,12 +63,16 @@ export const essqlSearchStrategyProvider = (): ISearchStrategy<
// If we still have rows to retrieve, continue requesting data
// using the cursor until we have everything
while (rows.length < count && body.cursor !== undefined) {
- response = await esClient.asCurrentUser.sql.query({
- format: 'json',
- body: {
- cursor: body.cursor,
+ // @ts-expect-error previous ts-ignore mess with the signature override
+ response = await esClient.asCurrentUser.sql.query(
+ {
+ format: 'json',
+ body: {
+ cursor: body.cursor,
+ },
},
- });
+ { meta: true }
+ );
body = response.body;
diff --git a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts
index 21b3357703866..ee17b2d3035b8 100644
--- a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts
+++ b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts
@@ -33,29 +33,27 @@ describe('Retrieve ES Fields', () => {
it(`returns 200 with fields from existing index/data view`, async () => {
const index = 'test';
const mockResults = {
- body: {
- indices: ['test'],
- fields: {
- '@timestamp': {
- date: {
- type: 'date',
- searchable: true,
- aggregatable: true,
- },
+ indices: ['test'],
+ fields: {
+ '@timestamp': {
+ date: {
+ type: 'date',
+ searchable: true,
+ aggregatable: true,
},
- name: {
- text: {
- type: 'text',
- searchable: true,
- aggregatable: false,
- },
+ },
+ name: {
+ text: {
+ type: 'text',
+ searchable: true,
+ aggregatable: false,
},
- products: {
- object: {
- type: 'object',
- searchable: false,
- aggregatable: false,
- },
+ },
+ products: {
+ object: {
+ type: 'object',
+ searchable: false,
+ aggregatable: false,
},
},
},
@@ -87,7 +85,7 @@ describe('Retrieve ES Fields', () => {
it(`returns 200 with empty object when index/data view has no fields`, async () => {
const index = 'test';
- const mockResults = { body: { indices: [index], fields: {} } };
+ const mockResults = { indices: [index], fields: {} };
const request = httpServerMock.createKibanaRequest({
method: 'get',
path,
@@ -111,10 +109,8 @@ describe('Retrieve ES Fields', () => {
const index = 'test';
const mockResults = {
- body: {
- indices: [index],
- fields: {},
- },
+ indices: [index],
+ fields: {},
};
const request = httpServerMock.createKibanaRequest({
diff --git a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts
index 340a6cdb902ff..f9523cee0ce4d 100644
--- a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts
+++ b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts
@@ -37,7 +37,7 @@ export function initializeESFieldsRoute(deps: RouteInitializerDeps) {
};
const esFields = await client.fieldCaps(config).then((resp) => {
- return mapValues(resp.body.fields, (types) => {
+ return mapValues(resp.fields, (types) => {
if (keys(types).length > 1) {
return 'conflict';
}
diff --git a/x-pack/plugins/cases/server/services/alerts/index.ts b/x-pack/plugins/cases/server/services/alerts/index.ts
index 7f966a471c725..e205899ead380 100644
--- a/x-pack/plugins/cases/server/services/alerts/index.ts
+++ b/x-pack/plugins/cases/server/services/alerts/index.ts
@@ -48,7 +48,7 @@ export class AlertService {
aggregations: builtAggs,
});
- return res.body.aggregations;
+ return res.aggregations;
} catch (error) {
const aggregationNames = aggregationBuilders.map((agg) => agg.getName());
diff --git a/x-pack/plugins/cross_cluster_replication/server/plugin.ts b/x-pack/plugins/cross_cluster_replication/server/plugin.ts
index 8041e0858ea84..9e4a8c484964b 100644
--- a/x-pack/plugins/cross_cluster_replication/server/plugin.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/plugin.ts
@@ -23,9 +23,7 @@ const ccrDataEnricher = async (indicesList: Index[], client: IScopedClusterClien
}
try {
- const {
- body: { follower_indices: followerIndices },
- } = await client.asCurrentUser.ccr.followInfo({
+ const { follower_indices: followerIndices } = await client.asCurrentUser.ccr.followInfo({
index: '_all',
});
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts
index dd1481b45f875..3fe320fe5bdd4 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_create_route.ts
@@ -56,7 +56,7 @@ export const registerCreateRoute = ({
}
try {
- const { body: responseBody } = await client.asCurrentUser.ccr.putAutoFollowPattern({
+ const responseBody = await client.asCurrentUser.ccr.putAutoFollowPattern({
name: id,
body,
});
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.test.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.test.ts
index 7b694cfe77efd..67ea716976417 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.test.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.test.ts
@@ -33,19 +33,17 @@ describe('[CCR API] Fetch all auto-follow patterns', () => {
it('deserializes the response from Elasticsearch', async () => {
const ccrAutoFollowPatternResponseMock = {
- body: {
- patterns: [
- {
- name: 'autoFollowPattern',
- pattern: {
- active: true,
- remote_cluster: 'remoteCluster',
- leader_index_patterns: ['leader*'],
- follow_index_pattern: 'follow',
- },
+ patterns: [
+ {
+ name: 'autoFollowPattern',
+ pattern: {
+ active: true,
+ remote_cluster: 'remoteCluster',
+ leader_index_patterns: ['leader*'],
+ follow_index_pattern: 'follow',
},
- ],
- },
+ },
+ ],
};
const routeContextMock = mockRouteContext({
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.ts
index 98ce37d1054bc..7cd9508bd7372 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_fetch_route.ts
@@ -26,9 +26,7 @@ export const registerFetchRoute = ({
const { client } = context.core.elasticsearch;
try {
- const {
- body: { patterns },
- } = await client.asCurrentUser.ccr.getAutoFollowPattern();
+ const { patterns } = await client.asCurrentUser.ccr.getAutoFollowPattern();
return response.ok({
body: {
// @ts-expect-error Once #98266 is merged, test this again.
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.test.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.test.ts
index 61fdd6e57ab7a..a2bf912a99728 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.test.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.test.ts
@@ -33,19 +33,17 @@ describe('[CCR API] Get one auto-follow pattern', () => {
it('should return a single resource even though ES returns an array with 1 item', async () => {
const ccrAutoFollowPatternResponseMock = {
- body: {
- patterns: [
- {
- name: 'autoFollowPattern',
- pattern: {
- active: true,
- remote_cluster: 'remoteCluster',
- leader_index_patterns: ['leader*'],
- follow_index_pattern: 'follow',
- },
+ patterns: [
+ {
+ name: 'autoFollowPattern',
+ pattern: {
+ active: true,
+ remote_cluster: 'remoteCluster',
+ leader_index_patterns: ['leader*'],
+ follow_index_pattern: 'follow',
},
- ],
- },
+ },
+ ],
};
const routeContextMock = mockRouteContext({
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.ts
index bc452982df63e..a5a70805d518d 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_get_route.ts
@@ -39,7 +39,7 @@ export const registerGetRoute = ({
name: id,
});
- const autoFollowPattern = result.body.patterns[0];
+ const autoFollowPattern = result.patterns[0];
return response.ok({
// @ts-expect-error Once #98266 is merged, test this again.
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.test.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.test.ts
index 5ada82049632b..19d165a80eb3b 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.test.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.test.ts
@@ -35,7 +35,7 @@ describe('[CCR API] Update auto-follow pattern', () => {
const routeContextMock = mockRouteContext({
ccr: {
// Just echo back what we send so we can inspect it.
- putAutoFollowPattern: jest.fn().mockImplementation((payload) => ({ body: payload })),
+ putAutoFollowPattern: jest.fn().mockImplementation((payload) => payload),
},
});
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts
index 81aaa59725e3a..98a716eb88cc6 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_update_route.ts
@@ -44,7 +44,7 @@ export const registerUpdateRoute = ({
const body = serializeAutoFollowPattern(request.body as AutoFollowPattern);
try {
- const { body: responseBody } = await client.asCurrentUser.ccr.putAutoFollowPattern({
+ const responseBody = await client.asCurrentUser.ccr.putAutoFollowPattern({
name: id,
body,
});
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts
index 600924e145039..dbee279a01336 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_permissions_route.ts
@@ -36,13 +36,12 @@ export const registerPermissionsRoute = ({
}
try {
- const {
- body: { has_all_requested: hasPermission, cluster },
- } = await client.asCurrentUser.security.hasPrivileges({
- body: {
- cluster: ['manage', 'manage_ccr'],
- },
- });
+ const { has_all_requested: hasPermission, cluster } =
+ await client.asCurrentUser.security.hasPrivileges({
+ body: {
+ cluster: ['manage', 'manage_ccr'],
+ },
+ });
const missingClusterPrivileges = Object.keys(cluster).reduce(
(permissions: string[], permissionName: string) => {
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_stats_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_stats_route.ts
index fa8f792afc419..bab31c53a83a2 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_stats_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/cross_cluster_replication/register_stats_route.ts
@@ -26,9 +26,7 @@ export const registerStatsRoute = ({
const { client } = context.core.elasticsearch;
try {
- const {
- body: { auto_follow_stats: autoFollowStats },
- } = await client.asCurrentUser.ccr.stats();
+ const { auto_follow_stats: autoFollowStats } = await client.asCurrentUser.ccr.stats();
return response.ok({
// @ts-expect-error Once #98266 is merged, test this again.
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts
index 9ddbf76cceed2..0aae8f9c115bc 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_create_route.ts
@@ -49,7 +49,7 @@ export const registerCreateRoute = ({
const body = removeEmptyFields(serializeFollowerIndex(rest as FollowerIndex));
try {
- const { body: responseBody } = await client.asCurrentUser.ccr.follow({
+ const responseBody = await client.asCurrentUser.ccr.follow({
index: name,
body,
});
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.test.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.test.ts
index e4063e1e64df5..3d818f40b0262 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.test.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.test.ts
@@ -33,69 +33,65 @@ describe('[CCR API] Fetch all follower indices', () => {
it('deserializes the response from Elasticsearch', async () => {
const ccrInfoMockResponse = {
- body: {
- follower_indices: [
- {
- follower_index: 'followerIndexName',
- remote_cluster: 'remoteCluster',
- leader_index: 'leaderIndex',
- status: 'active',
- parameters: {
- max_read_request_operation_count: 1,
- max_outstanding_read_requests: 1,
- max_read_request_size: '1b',
- max_write_request_operation_count: 1,
- max_write_request_size: '1b',
- max_outstanding_write_requests: 1,
- max_write_buffer_count: 1,
- max_write_buffer_size: '1b',
- max_retry_delay: '1s',
- read_poll_timeout: '1s',
- },
+ follower_indices: [
+ {
+ follower_index: 'followerIndexName',
+ remote_cluster: 'remoteCluster',
+ leader_index: 'leaderIndex',
+ status: 'active',
+ parameters: {
+ max_read_request_operation_count: 1,
+ max_outstanding_read_requests: 1,
+ max_read_request_size: '1b',
+ max_write_request_operation_count: 1,
+ max_write_request_size: '1b',
+ max_outstanding_write_requests: 1,
+ max_write_buffer_count: 1,
+ max_write_buffer_size: '1b',
+ max_retry_delay: '1s',
+ read_poll_timeout: '1s',
},
- ],
- },
+ },
+ ],
};
// These stats correlate to the above follower indices.
const ccrStatsMockResponse = {
- body: {
- follow_stats: {
- indices: [
- {
- index: 'followerIndexName',
- shards: [
- {
- shard_id: 1,
- leader_index: 'leaderIndex',
- leader_global_checkpoint: 1,
- leader_max_seq_no: 1,
- follower_global_checkpoint: 1,
- follower_max_seq_no: 1,
- last_requested_seq_no: 1,
- outstanding_read_requests: 1,
- outstanding_write_requests: 1,
- write_buffer_operation_count: 1,
- write_buffer_size_in_bytes: 1,
- follower_mapping_version: 1,
- follower_settings_version: 1,
- total_read_time_millis: 1,
- total_read_remote_exec_time_millis: 1,
- successful_read_requests: 1,
- failed_read_requests: 1,
- operations_read: 1,
- bytes_read: 1,
- total_write_time_millis: 1,
- successful_write_requests: 1,
- failed_write_requests: 1,
- operations_written: 1,
- read_exceptions: 1,
- time_since_last_read_millis: 1,
- },
- ],
- },
- ],
- },
+ follow_stats: {
+ indices: [
+ {
+ index: 'followerIndexName',
+ shards: [
+ {
+ shard_id: 1,
+ leader_index: 'leaderIndex',
+ leader_global_checkpoint: 1,
+ leader_max_seq_no: 1,
+ follower_global_checkpoint: 1,
+ follower_max_seq_no: 1,
+ last_requested_seq_no: 1,
+ outstanding_read_requests: 1,
+ outstanding_write_requests: 1,
+ write_buffer_operation_count: 1,
+ write_buffer_size_in_bytes: 1,
+ follower_mapping_version: 1,
+ follower_settings_version: 1,
+ total_read_time_millis: 1,
+ total_read_remote_exec_time_millis: 1,
+ successful_read_requests: 1,
+ failed_read_requests: 1,
+ operations_read: 1,
+ bytes_read: 1,
+ total_write_time_millis: 1,
+ successful_write_requests: 1,
+ failed_write_requests: 1,
+ operations_written: 1,
+ read_exceptions: 1,
+ time_since_last_read_millis: 1,
+ },
+ ],
+ },
+ ],
},
};
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.ts
index b4d7ead75e830..7bbe2c8c05d4a 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_fetch_route.ts
@@ -26,14 +26,12 @@ export const registerFetchRoute = ({
const { client } = context.core.elasticsearch;
try {
- const {
- body: { follower_indices: followerIndices },
- } = await client.asCurrentUser.ccr.followInfo({ index: '_all' });
+ const { follower_indices: followerIndices } = await client.asCurrentUser.ccr.followInfo({
+ index: '_all',
+ });
const {
- body: {
- follow_stats: { indices: followerIndicesStats },
- },
+ follow_stats: { indices: followerIndicesStats },
} = await client.asCurrentUser.ccr.stats();
const followerIndicesStatsMap = followerIndicesStats.reduce((map: any, stats: any) => {
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.test.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.test.ts
index 493703ca6de27..a0af8827b8744 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.test.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.test.ts
@@ -33,68 +33,64 @@ describe('[CCR API] Get one follower index', () => {
it('should return a single resource even though ES returns an array with 1 item', async () => {
const ccrInfoMockResponse = {
- body: {
- follower_indices: [
- {
- follower_index: 'followerIndexName',
- remote_cluster: 'remoteCluster',
- leader_index: 'leaderIndex',
- status: 'active',
- parameters: {
- max_read_request_operation_count: 1,
- max_outstanding_read_requests: 1,
- max_read_request_size: '1b',
- max_write_request_operation_count: 1,
- max_write_request_size: '1b',
- max_outstanding_write_requests: 1,
- max_write_buffer_count: 1,
- max_write_buffer_size: '1b',
- max_retry_delay: '1s',
- read_poll_timeout: '1s',
- },
+ follower_indices: [
+ {
+ follower_index: 'followerIndexName',
+ remote_cluster: 'remoteCluster',
+ leader_index: 'leaderIndex',
+ status: 'active',
+ parameters: {
+ max_read_request_operation_count: 1,
+ max_outstanding_read_requests: 1,
+ max_read_request_size: '1b',
+ max_write_request_operation_count: 1,
+ max_write_request_size: '1b',
+ max_outstanding_write_requests: 1,
+ max_write_buffer_count: 1,
+ max_write_buffer_size: '1b',
+ max_retry_delay: '1s',
+ read_poll_timeout: '1s',
},
- ],
- },
+ },
+ ],
};
// These stats correlate to the above follower indices.
const ccrFollowerIndexStatsMockResponse = {
- body: {
- indices: [
- {
- index: 'followerIndexName',
- shards: [
- {
- shard_id: 1,
- leader_index: 'leaderIndex',
- leader_global_checkpoint: 1,
- leader_max_seq_no: 1,
- follower_global_checkpoint: 1,
- follower_max_seq_no: 1,
- last_requested_seq_no: 1,
- outstanding_read_requests: 1,
- outstanding_write_requests: 1,
- write_buffer_operation_count: 1,
- write_buffer_size_in_bytes: 1,
- follower_mapping_version: 1,
- follower_settings_version: 1,
- total_read_time_millis: 1,
- total_read_remote_exec_time_millis: 1,
- successful_read_requests: 1,
- failed_read_requests: 1,
- operations_read: 1,
- bytes_read: 1,
- total_write_time_millis: 1,
- successful_write_requests: 1,
- failed_write_requests: 1,
- operations_written: 1,
- read_exceptions: 1,
- time_since_last_read_millis: 1,
- },
- ],
- },
- ],
- },
+ indices: [
+ {
+ index: 'followerIndexName',
+ shards: [
+ {
+ shard_id: 1,
+ leader_index: 'leaderIndex',
+ leader_global_checkpoint: 1,
+ leader_max_seq_no: 1,
+ follower_global_checkpoint: 1,
+ follower_max_seq_no: 1,
+ last_requested_seq_no: 1,
+ outstanding_read_requests: 1,
+ outstanding_write_requests: 1,
+ write_buffer_operation_count: 1,
+ write_buffer_size_in_bytes: 1,
+ follower_mapping_version: 1,
+ follower_settings_version: 1,
+ total_read_time_millis: 1,
+ total_read_remote_exec_time_millis: 1,
+ successful_read_requests: 1,
+ failed_read_requests: 1,
+ operations_read: 1,
+ bytes_read: 1,
+ total_write_time_millis: 1,
+ successful_write_requests: 1,
+ failed_write_requests: 1,
+ operations_written: 1,
+ read_exceptions: 1,
+ time_since_last_read_millis: 1,
+ },
+ ],
+ },
+ ],
};
const routeContextMock = mockRouteContext({
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.ts
index 21cb9e08a6160..c33ed97c289f0 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_get_route.ts
@@ -34,9 +34,9 @@ export const registerGetRoute = ({
const { id } = request.params;
try {
- const {
- body: { follower_indices: followerIndices },
- } = await client.asCurrentUser.ccr.followInfo({ index: id });
+ const { follower_indices: followerIndices } = await client.asCurrentUser.ccr.followInfo({
+ index: id,
+ });
const followerIndexInfo = followerIndices && followerIndices[0];
@@ -55,9 +55,9 @@ export const registerGetRoute = ({
}),
});
} else {
- const {
- body: { indices: followerIndicesStats },
- } = await client.asCurrentUser.ccr.followStats({ index: id });
+ const { indices: followerIndicesStats } = await client.asCurrentUser.ccr.followStats({
+ index: id,
+ });
return response.ok({
// @ts-expect-error Once #98266 is merged, test this again.
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.test.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.test.ts
index 92b9c3dded08e..d2cd579687106 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.test.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.test.ts
@@ -34,11 +34,9 @@ describe('[CCR API] Update follower index', () => {
it('should serialize the payload before sending it to Elasticsearch', async () => {
const routeContextMock = mockRouteContext({
ccr: {
- followInfo: jest
- .fn()
- .mockResolvedValueOnce({ body: { follower_indices: [{ status: 'paused' }] } }),
+ followInfo: jest.fn().mockResolvedValueOnce({ follower_indices: [{ status: 'paused' }] }),
// Just echo back what we send so we can inspect it.
- resumeFollow: jest.fn().mockImplementation((payload) => ({ body: payload })),
+ resumeFollow: jest.fn().mockImplementation((payload) => payload),
},
});
diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts
index 5029c8be96043..0bacbd5fb3450 100644
--- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts
+++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_update_route.ts
@@ -49,9 +49,9 @@ export const registerUpdateRoute = ({
// We need to first pause the follower and then resume it by passing the advanced settings
try {
- const {
- body: { follower_indices: followerIndices },
- } = await client.asCurrentUser.ccr.followInfo({ index: id });
+ const { follower_indices: followerIndices } = await client.asCurrentUser.ccr.followInfo({
+ index: id,
+ });
const followerIndexInfo = followerIndices && followerIndices[0];
@@ -72,7 +72,7 @@ export const registerUpdateRoute = ({
serializeAdvancedSettings(request.body as FollowerIndexAdvancedSettings)
);
- const { body: responseBody } = await client.asCurrentUser.ccr.resumeFollow({
+ const responseBody = await client.asCurrentUser.ccr.resumeFollow({
index: id,
body,
});
diff --git a/x-pack/plugins/data_enhanced/server/collectors/fetch.test.ts b/x-pack/plugins/data_enhanced/server/collectors/fetch.test.ts
index 47e6fb05c2329..ed079fe948750 100644
--- a/x-pack/plugins/data_enhanced/server/collectors/fetch.test.ts
+++ b/x-pack/plugins/data_enhanced/server/collectors/fetch.test.ts
@@ -5,17 +5,13 @@
* 2.0.
*/
-import {
- ElasticsearchClient,
- SavedObjectsErrorHelpers,
- Logger,
-} from '../../../../../src/core/server';
+import { SavedObjectsErrorHelpers, Logger } from '../../../../../src/core/server';
import { fetchProvider } from './fetch';
import { elasticsearchServiceMock } from '../../../../../src/core/server/mocks';
describe('fetchProvider', () => {
let fetchFn: any;
- let esClient: jest.Mocked;
+ let esClient: ReturnType;
let mockLogger: Logger;
beforeEach(async () => {
@@ -29,13 +25,10 @@ describe('fetchProvider', () => {
});
test('returns when ES returns no results', async () => {
- esClient.search.mockResolvedValue({
- statusCode: 200,
- body: {
- aggregations: {
- persisted: {
- buckets: [],
- },
+ esClient.search.mockResponse({
+ aggregations: {
+ persisted: {
+ buckets: [],
},
},
} as any);
@@ -60,22 +53,19 @@ describe('fetchProvider', () => {
});
test('returns when ES returns full buckets', async () => {
- esClient.search.mockResolvedValue({
- statusCode: 200,
- body: {
- aggregations: {
- persisted: {
- buckets: [
- {
- key_as_string: 'true',
- doc_count: 10,
- },
- {
- key_as_string: 'false',
- doc_count: 7,
- },
- ],
- },
+ esClient.search.mockResponse({
+ aggregations: {
+ persisted: {
+ buckets: [
+ {
+ key_as_string: 'true',
+ doc_count: 10,
+ },
+ {
+ key_as_string: 'false',
+ doc_count: 7,
+ },
+ ],
},
},
} as any);
diff --git a/x-pack/plugins/data_enhanced/server/collectors/fetch.ts b/x-pack/plugins/data_enhanced/server/collectors/fetch.ts
index b566ceb9065d2..82597a9003051 100644
--- a/x-pack/plugins/data_enhanced/server/collectors/fetch.ts
+++ b/x-pack/plugins/data_enhanced/server/collectors/fetch.ts
@@ -18,7 +18,7 @@ interface SessionPersistedTermsBucket {
export function fetchProvider(kibanaIndex: string, logger: Logger) {
return async ({ esClient }: CollectorFetchContext): Promise => {
try {
- const { body: esResponse } = await esClient.search({
+ const esResponse = await esClient.search({
index: kibanaIndex,
body: {
size: 0,
diff --git a/x-pack/plugins/data_enhanced/server/search/session/check_non_persisted_sessions.test.ts b/x-pack/plugins/data_enhanced/server/search/session/check_non_persisted_sessions.test.ts
index 4d9ecb9221709..85bfbc8d037db 100644
--- a/x-pack/plugins/data_enhanced/server/search/session/check_non_persisted_sessions.test.ts
+++ b/x-pack/plugins/data_enhanced/server/search/session/check_non_persisted_sessions.test.ts
@@ -488,7 +488,7 @@ describe('checkNonPersistedSessions', () => {
config
);
- expect(mockClient.asyncSearch.status).toBeCalledWith({ id: 'search-id' });
+ expect(mockClient.asyncSearch.status).toBeCalledWith({ id: 'search-id' }, { meta: true });
const [updateInput] = savedObjectsClient.bulkUpdate.mock.calls[0];
const updatedAttributes = updateInput[0] as SavedObjectsBulkUpdateObject;
expect(updatedAttributes.namespace).toBe('awesome');
@@ -532,7 +532,7 @@ describe('checkNonPersistedSessions', () => {
config
);
- expect(mockClient.asyncSearch.status).toBeCalledWith({ id: 'search-id' });
+ expect(mockClient.asyncSearch.status).toBeCalledWith({ id: 'search-id' }, { meta: true });
const [updateInput] = savedObjectsClient.bulkUpdate.mock.calls[0];
const updatedAttributes = updateInput[0].attributes as SearchSessionSavedObjectAttributes;
expect(updatedAttributes.status).toBe(SearchSessionStatus.COMPLETE);
diff --git a/x-pack/plugins/data_enhanced/server/search/session/get_search_status.ts b/x-pack/plugins/data_enhanced/server/search/session/get_search_status.ts
index a49dc30b84fb5..abfe089e82a38 100644
--- a/x-pack/plugins/data_enhanced/server/search/session/get_search_status.ts
+++ b/x-pack/plugins/data_enhanced/server/search/session/get_search_status.ts
@@ -22,7 +22,8 @@ export async function getSearchStatus(
const apiResponse: TransportResult = await client.asyncSearch.status(
{
id: asyncId,
- }
+ },
+ { meta: true }
);
const response = apiResponse.body;
if ((response.is_partial && !response.is_running) || response.completion_status >= 400) {
diff --git a/x-pack/plugins/data_enhanced/server/search/session/update_session_status.test.ts b/x-pack/plugins/data_enhanced/server/search/session/update_session_status.test.ts
index d9e3fa6f8cab3..3b6b0a7a16d85 100644
--- a/x-pack/plugins/data_enhanced/server/search/session/update_session_status.test.ts
+++ b/x-pack/plugins/data_enhanced/server/search/session/update_session_status.test.ts
@@ -186,7 +186,7 @@ describe('bulkUpdateSessions', () => {
expect(updated).toBeTruthy();
- expect(mockClient.asyncSearch.status).toBeCalledWith({ id: 'search-id' });
+ expect(mockClient.asyncSearch.status).toBeCalledWith({ id: 'search-id' }, { meta: true });
expect(so.attributes.status).toBe(SearchSessionStatus.COMPLETE);
expect(so.attributes.status).toBe(SearchSessionStatus.COMPLETE);
expect(so.attributes.touched).not.toBe('123');
diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts
index 0d4f4136b42ed..5ff3b6c481d74 100644
--- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts
+++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts
@@ -5,7 +5,6 @@
* 2.0.
*/
-import { ElasticsearchClient } from 'src/core/server';
import { elasticsearchServiceMock, loggingSystemMock } from 'src/core/server/mocks';
import {
ClusterClientAdapter,
@@ -15,14 +14,12 @@ import {
import { findOptionsSchema } from '../event_log_client';
import { delay } from '../lib/delay';
import { times } from 'lodash';
-import { DeeplyMockedKeys } from '@kbn/utility-types/jest';
import type * as estypes from '@elastic/elasticsearch/lib/api/types';
-import type { TransportResult } from '@elastic/elasticsearch';
type MockedLogger = ReturnType;
let logger: MockedLogger;
-let clusterClient: DeeplyMockedKeys;
+let clusterClient: ReturnType;
let clusterClientAdapter: IClusterClientAdapter;
beforeEach(() => {
@@ -191,7 +188,7 @@ describe('doesIlmPolicyExist', () => {
describe('createIlmPolicy', () => {
test('should call cluster client with given policy', async () => {
- clusterClient.transport.request.mockResolvedValue(asApiResponse({ success: true }));
+ clusterClient.transport.request.mockResolvedValue({ success: true });
await clusterClientAdapter.createIlmPolicy('foo', { args: true });
expect(clusterClient.transport.request).toHaveBeenCalledWith({
method: 'PUT',
@@ -217,20 +214,20 @@ describe('doesIndexTemplateExist', () => {
});
test('should return true when call cluster to legacy template API returns true', async () => {
- clusterClient.indices.existsTemplate.mockResolvedValue(asApiResponse(true));
- clusterClient.indices.existsIndexTemplate.mockResolvedValue(asApiResponse(false));
+ clusterClient.indices.existsTemplate.mockResponse(true);
+ clusterClient.indices.existsIndexTemplate.mockResponse(false);
await expect(clusterClientAdapter.doesIndexTemplateExist('foo')).resolves.toEqual(true);
});
test('should return true when call cluster to index template API returns true', async () => {
- clusterClient.indices.existsTemplate.mockResolvedValue(asApiResponse(false));
- clusterClient.indices.existsIndexTemplate.mockResolvedValue(asApiResponse(true));
+ clusterClient.indices.existsTemplate.mockResponse(false);
+ clusterClient.indices.existsIndexTemplate.mockResponse(true);
await expect(clusterClientAdapter.doesIndexTemplateExist('foo')).resolves.toEqual(true);
});
test('should return false when both call cluster calls returns false', async () => {
- clusterClient.indices.existsTemplate.mockResolvedValue(asApiResponse(false));
- clusterClient.indices.existsIndexTemplate.mockResolvedValue(asApiResponse(false));
+ clusterClient.indices.existsTemplate.mockResponse(false);
+ clusterClient.indices.existsIndexTemplate.mockResponse(false);
await expect(clusterClientAdapter.doesIndexTemplateExist('foo')).resolves.toEqual(false);
});
@@ -265,8 +262,8 @@ describe('createIndexTemplate', () => {
test(`should throw error if index template still doesn't exist after error is thrown`, async () => {
clusterClient.indices.putIndexTemplate.mockRejectedValueOnce(new Error('Fail'));
- clusterClient.indices.existsTemplate.mockResolvedValueOnce(asApiResponse(false));
- clusterClient.indices.existsIndexTemplate.mockResolvedValueOnce(asApiResponse(false));
+ clusterClient.indices.existsTemplate.mockResponseOnce(false);
+ clusterClient.indices.existsIndexTemplate.mockResponseOnce(false);
await expect(
clusterClientAdapter.createIndexTemplate('foo', { args: true })
).rejects.toThrowErrorMatchingInlineSnapshot(`"error creating index template: Fail"`);
@@ -274,7 +271,7 @@ describe('createIndexTemplate', () => {
test('should not throw error if index template exists after error is thrown', async () => {
clusterClient.indices.putIndexTemplate.mockRejectedValueOnce(new Error('Fail'));
- clusterClient.indices.existsTemplate.mockResolvedValueOnce(asApiResponse(true));
+ clusterClient.indices.existsTemplate.mockResponseOnce(true);
await clusterClientAdapter.createIndexTemplate('foo', { args: true });
});
});
@@ -300,9 +297,7 @@ describe('getExistingLegacyIndexTemplates', () => {
aliases: {},
},
};
- clusterClient.indices.getTemplate.mockResolvedValue(
- asApiResponse(response)
- );
+ clusterClient.indices.getTemplate.mockResponse(response);
await expect(clusterClientAdapter.getExistingLegacyIndexTemplates('foo*')).resolves.toEqual(
response
);
@@ -378,9 +373,7 @@ describe('getExistingIndices', () => {
},
},
};
- clusterClient.indices.getSettings.mockResolvedValue(
- asApiResponse(response)
- );
+ clusterClient.indices.getSettings.mockResponse(response as estypes.IndicesGetSettingsResponse);
await expect(clusterClientAdapter.getExistingIndices('foo*')).resolves.toEqual(response);
});
@@ -436,9 +429,7 @@ describe('getExistingIndexAliases', () => {
},
},
};
- clusterClient.indices.getAlias.mockResolvedValue(
- asApiResponse(response)
- );
+ clusterClient.indices.getAlias.mockResponse(response as estypes.IndicesGetAliasResponse);
await expect(clusterClientAdapter.getExistingIndexAliases('foo*')).resolves.toEqual(response);
});
@@ -524,12 +515,12 @@ describe('doesAliasExist', () => {
});
test('should return true when call cluster returns true', async () => {
- clusterClient.indices.existsAlias.mockResolvedValueOnce(asApiResponse(true));
+ clusterClient.indices.existsAlias.mockResponse(true);
await expect(clusterClientAdapter.doesAliasExist('foo')).resolves.toEqual(true);
});
test('should return false when call cluster returns false', async () => {
- clusterClient.indices.existsAlias.mockResolvedValueOnce(asApiResponse(false));
+ clusterClient.indices.existsAlias.mockResponse(false);
await expect(clusterClientAdapter.doesAliasExist('foo')).resolves.toEqual(false);
});
@@ -577,22 +568,20 @@ describe('queryEventsBySavedObject', () => {
const DEFAULT_OPTIONS = findOptionsSchema.validate({});
test('should call cluster with proper arguments with non-default namespace', async () => {
- clusterClient.search.mockResolvedValue(
- asApiResponse({
- hits: {
- hits: [],
- total: { relation: 'eq', value: 0 },
- },
- took: 0,
- timed_out: false,
- _shards: {
- failed: 0,
- successful: 0,
- total: 0,
- skipped: 0,
- },
- })
- );
+ clusterClient.search.mockResponse({
+ hits: {
+ hits: [],
+ total: { relation: 'eq', value: 0 },
+ },
+ took: 0,
+ timed_out: false,
+ _shards: {
+ failed: 0,
+ successful: 0,
+ total: 0,
+ skipped: 0,
+ },
+ });
await clusterClientAdapter.queryEventsBySavedObjects({
index: 'index-name',
namespace: 'namespace',
@@ -789,22 +778,20 @@ describe('queryEventsBySavedObject', () => {
});
test('should call cluster with proper arguments with default namespace', async () => {
- clusterClient.search.mockResolvedValue(
- asApiResponse({
- hits: {
- hits: [],
- total: { relation: 'eq', value: 0 },
- },
- took: 0,
- timed_out: false,
- _shards: {
- failed: 0,
- successful: 0,
- total: 0,
- skipped: 0,
- },
- })
- );
+ clusterClient.search.mockResponse({
+ hits: {
+ hits: [],
+ total: { relation: 'eq', value: 0 },
+ },
+ took: 0,
+ timed_out: false,
+ _shards: {
+ failed: 0,
+ successful: 0,
+ total: 0,
+ skipped: 0,
+ },
+ });
await clusterClientAdapter.queryEventsBySavedObjects({
index: 'index-name',
namespace: undefined,
@@ -908,22 +895,20 @@ describe('queryEventsBySavedObject', () => {
});
test('should call cluster with sort', async () => {
- clusterClient.search.mockResolvedValue(
- asApiResponse({
- hits: {
- hits: [],
- total: { relation: 'eq', value: 0 },
- },
- took: 0,
- timed_out: false,
- _shards: {
- failed: 0,
- successful: 0,
- total: 0,
- skipped: 0,
- },
- })
- );
+ clusterClient.search.mockResponse({
+ hits: {
+ hits: [],
+ total: { relation: 'eq', value: 0 },
+ },
+ took: 0,
+ timed_out: false,
+ _shards: {
+ failed: 0,
+ successful: 0,
+ total: 0,
+ skipped: 0,
+ },
+ });
await clusterClientAdapter.queryEventsBySavedObjects({
index: 'index-name',
namespace: 'namespace',
@@ -942,22 +927,20 @@ describe('queryEventsBySavedObject', () => {
});
test('supports open ended date', async () => {
- clusterClient.search.mockResolvedValue(
- asApiResponse({
- hits: {
- hits: [],
- total: { relation: 'eq', value: 0 },
- },
- took: 0,
- timed_out: false,
- _shards: {
- failed: 0,
- successful: 0,
- total: 0,
- skipped: 0,
- },
- })
- );
+ clusterClient.search.mockResponse({
+ hits: {
+ hits: [],
+ total: { relation: 'eq', value: 0 },
+ },
+ took: 0,
+ timed_out: false,
+ _shards: {
+ failed: 0,
+ successful: 0,
+ total: 0,
+ skipped: 0,
+ },
+ });
const start = '2020-07-08T00:52:28.350Z';
@@ -1069,22 +1052,20 @@ describe('queryEventsBySavedObject', () => {
});
test('supports optional date range', async () => {
- clusterClient.search.mockResolvedValue(
- asApiResponse({
- hits: {
- hits: [],
- total: { relation: 'eq', value: 0 },
- },
- took: 0,
- timed_out: false,
- _shards: {
- failed: 0,
- successful: 0,
- total: 0,
- skipped: 0,
- },
- })
- );
+ clusterClient.search.mockResponse({
+ hits: {
+ hits: [],
+ total: { relation: 'eq', value: 0 },
+ },
+ took: 0,
+ timed_out: false,
+ _shards: {
+ failed: 0,
+ successful: 0,
+ total: 0,
+ skipped: 0,
+ },
+ });
const start = '2020-07-08T00:52:28.350Z';
const end = '2020-07-08T00:00:00.000Z';
@@ -1254,12 +1235,6 @@ type RetryableFunction = () => boolean;
const RETRY_UNTIL_DEFAULT_COUNT = 20;
const RETRY_UNTIL_DEFAULT_WAIT = 1000; // milliseconds
-function asApiResponse(body: T): TransportResult {
- return {
- body,
- } as TransportResult;
-}
-
async function retryUntil(
label: string,
fn: RetryableFunction,
diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts
index dd740aa5533b9..010d162c62ea1 100644
--- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts
+++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts
@@ -120,9 +120,9 @@ export class ClusterClientAdapter {
try {
const esClient = await this.elasticsearchClientPromise;
- const { body: legacyResult } = await esClient.indices.existsTemplate({ name });
- const { body: indexTemplateResult } = await esClient.indices.existsIndexTemplate({ name });
+ const legacyResult = await esClient.indices.existsTemplate({ name });
+ const indexTemplateResult = await esClient.indices.existsIndexTemplate({ name });
return (legacyResult as boolean) || (indexTemplateResult as boolean);
} catch (err) {
throw new Error(`error checking existence of index template: ${err.message}`);
@@ -200,11 +200,7 @@ export class ClusterClientAdapter {
try {
const esClient = await this.elasticsearchClientPromise;
- const { body: templates } = await esClient.indices.getTemplate(
- { name: indexTemplatePattern },
- { ignore: [404] }
- );
- return templates;
+ return await esClient.indices.getTemplate({ name: indexTemplatePattern }, { ignore: [404] });
} catch (err) {
throw new Error(`error getting existing legacy index templates: ${err.message}`);
}
@@ -238,11 +234,7 @@ export class ClusterClientAdapter {
try {
const esClient = await this.elasticsearchClientPromise;
- const { body: indexSettings } = await esClient.indices.getSettings(
- { index: indexPattern },
- { ignore: [404] }
- );
- return indexSettings;
+ return await esClient.indices.getSettings({ index: indexPattern }, { ignore: [404] });
} catch (err) {
throw new Error(
`error getting existing indices matching pattern ${indexPattern}: ${err.message}`
@@ -269,11 +261,7 @@ export class ClusterClientAdapter {
try {
const esClient = await this.elasticsearchClientPromise;
- const { body: indexAliases } = await esClient.indices.getAlias(
- { index: indexPattern },
- { ignore: [404] }
- );
- return indexAliases;
+ return await esClient.indices.getAlias({ index: indexPattern }, { ignore: [404] });
} catch (err) {
throw new Error(
`error getting existing index aliases matching pattern ${indexPattern}: ${err.message}`
@@ -318,7 +306,7 @@ export class ClusterClientAdapter {
try {
const esClient = await this.elasticsearchClientPromise;
- const { body } = await esClient.indices.existsAlias({ name });
+ const body = await esClient.indices.existsAlias({ name });
return body as boolean;
} catch (err) {
throw new Error(`error checking existance of initial index: ${err.message}`);
@@ -527,9 +515,7 @@ export class ClusterClientAdapter({
index,
track_total_hits: true,
diff --git a/x-pack/plugins/event_log/server/es/context.test.ts b/x-pack/plugins/event_log/server/es/context.test.ts
index 97d68b64d1f39..f6b4178ce7f11 100644
--- a/x-pack/plugins/event_log/server/es/context.test.ts
+++ b/x-pack/plugins/event_log/server/es/context.test.ts
@@ -6,19 +6,18 @@
*/
import { createEsContext } from './context';
-import { ElasticsearchClient, Logger } from '../../../../../src/core/server';
+import { Logger } from '../../../../../src/core/server';
import { elasticsearchServiceMock, loggingSystemMock } from '../../../../../src/core/server/mocks';
-import { DeeplyMockedKeys } from '@kbn/utility-types/jest';
-import type { TransportResult } from '@elastic/elasticsearch';
+
jest.mock('../lib/../../../../package.json', () => ({ version: '1.2.3' }));
jest.mock('./init');
let logger: Logger;
-let elasticsearchClient: DeeplyMockedKeys;
+let elasticsearchClient: ReturnType;
beforeEach(() => {
logger = loggingSystemMock.createLogger();
- elasticsearchClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
+ elasticsearchClient = elasticsearchServiceMock.createElasticsearchClient();
});
describe('createEsContext', () => {
@@ -64,9 +63,9 @@ describe('createEsContext', () => {
elasticsearchClientPromise: Promise.resolve(elasticsearchClient),
});
- elasticsearchClient.indices.existsTemplate.mockResolvedValue(asApiResponse(false));
- elasticsearchClient.indices.existsIndexTemplate.mockResolvedValue(asApiResponse(false));
- elasticsearchClient.indices.existsAlias.mockResolvedValue(asApiResponse(false));
+ elasticsearchClient.indices.existsTemplate.mockResponse(false);
+ elasticsearchClient.indices.existsIndexTemplate.mockResponse(false);
+ elasticsearchClient.indices.existsAlias.mockResponse(false);
const doesAliasExist = await context.esAdapter.doesAliasExist(context.esNames.alias);
expect(doesAliasExist).toBeFalsy();
@@ -83,7 +82,7 @@ describe('createEsContext', () => {
kibanaVersion: '1.2.3',
elasticsearchClientPromise: Promise.resolve(elasticsearchClient),
});
- elasticsearchClient.indices.existsTemplate.mockResolvedValue(asApiResponse(true));
+ elasticsearchClient.indices.existsTemplate.mockResponse(true);
context.initialize();
const doesIlmPolicyExist = await context.esAdapter.doesIlmPolicyExist(
@@ -113,9 +112,3 @@ describe('createEsContext', () => {
expect(success).toBe(false);
});
});
-
-function asApiResponse(body: T): TransportResult {
- return {
- body,
- } as TransportResult;
-}
diff --git a/x-pack/plugins/file_upload/server/analyze_file.tsx b/x-pack/plugins/file_upload/server/analyze_file.tsx
index cdb0bddecb395..ae2b1aeef81bd 100644
--- a/x-pack/plugins/file_upload/server/analyze_file.tsx
+++ b/x-pack/plugins/file_upload/server/analyze_file.tsx
@@ -19,7 +19,7 @@ export async function analyzeFile(
overrides: InputOverrides
): Promise {
overrides.explain = overrides.explain === undefined ? 'true' : overrides.explain;
- const { body } = await client.asInternalUser.textStructure.findStructure(
+ const body = await client.asInternalUser.textStructure.findStructure(
{
body: data,
...overrides,
diff --git a/x-pack/plugins/file_upload/server/get_time_field_range.ts b/x-pack/plugins/file_upload/server/get_time_field_range.ts
index 84fc6ac002008..9da8e7fb2b7e4 100644
--- a/x-pack/plugins/file_upload/server/get_time_field_range.ts
+++ b/x-pack/plugins/file_upload/server/get_time_field_range.ts
@@ -22,9 +22,7 @@ export async function getTimeFieldRange(
}> {
const obj = { success: true, start: { epoch: 0, string: '' }, end: { epoch: 0, string: '' } };
- const {
- body: { aggregations },
- } = await client.asCurrentUser.search({
+ const { aggregations } = await client.asCurrentUser.search({
index,
size: 0,
body: {
diff --git a/x-pack/plugins/file_upload/server/import_data.ts b/x-pack/plugins/file_upload/server/import_data.ts
index c2975fca959f0..c093cfcee190c 100644
--- a/x-pack/plugins/file_upload/server/import_data.ts
+++ b/x-pack/plugins/file_upload/server/import_data.ts
@@ -120,7 +120,7 @@ export function importDataProvider({ asCurrentUser }: IScopedClusterClient) {
settings.pipeline = pipelineId;
}
- const { body: resp } = await asCurrentUser.bulk(settings, { maxRetries: 0 });
+ const resp = await asCurrentUser.bulk(settings, { maxRetries: 0 });
if (resp.errors) {
throw resp;
} else {
@@ -153,8 +153,7 @@ export function importDataProvider({ asCurrentUser }: IScopedClusterClient) {
}
async function createPipeline(id: string, pipeline: any) {
- const { body } = await asCurrentUser.ingest.putPipeline({ id, body: pipeline });
- return body;
+ return await asCurrentUser.ingest.putPipeline({ id, body: pipeline });
}
function getFailures(items: any[], data: InputData): ImportFailure[] {
diff --git a/x-pack/plugins/file_upload/server/routes.ts b/x-pack/plugins/file_upload/server/routes.ts
index e8d32152c8afc..eeb22faefb1ca 100644
--- a/x-pack/plugins/file_upload/server/routes.ts
+++ b/x-pack/plugins/file_upload/server/routes.ts
@@ -182,8 +182,9 @@ export function fileUploadRoutes(coreSetup: CoreSetup, logge
},
async (context, request, response) => {
try {
- const { body: indexExists } =
- await context.core.elasticsearch.client.asCurrentUser.indices.exists(request.body);
+ const indexExists = await context.core.elasticsearch.client.asCurrentUser.indices.exists(
+ request.body
+ );
return response.ok({ body: { exists: indexExists } });
} catch (e) {
return response.customError(wrapError(e));
diff --git a/x-pack/plugins/fleet/server/routes/app/index.ts b/x-pack/plugins/fleet/server/routes/app/index.ts
index b9f9f0ee494fc..079850dc07478 100644
--- a/x-pack/plugins/fleet/server/routes/app/index.ts
+++ b/x-pack/plugins/fleet/server/routes/app/index.ts
@@ -39,9 +39,7 @@ export const getCheckPermissionsHandler: FleetRequestHandler<
// check the manage_service_account cluster privilege
else if (request.query.fleetServerSetup) {
const esClient = context.core.elasticsearch.client.asCurrentUser;
- const {
- body: { has_all_requested: hasAllPrivileges },
- } = await esClient.security.hasPrivileges({
+ const { has_all_requested: hasAllPrivileges } = await esClient.security.hasPrivileges({
body: { cluster: ['manage_service_account'] },
});
@@ -63,7 +61,7 @@ export const generateServiceTokenHandler: RequestHandler = async (context, reque
// Generate the fleet server service token as the current user as the internal user do not have the correct permissions
const esClient = context.core.elasticsearch.client.asCurrentUser;
try {
- const { body: tokenResponse } = await esClient.transport.request<{
+ const tokenResponse = await esClient.transport.request<{
created?: boolean;
token?: GenerateServiceTokenResponse;
}>({
diff --git a/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts b/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts
index bc64d9bf02f0c..070def907bcff 100644
--- a/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts
+++ b/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts
@@ -15,6 +15,7 @@ import { getPackageSavedObjects } from '../../services/epm/packages/get';
import { defaultIngestErrorHandler } from '../../errors';
const DATA_STREAM_INDEX_PATTERN = 'logs-*-*,metrics-*-*,traces-*-*,synthetics-*-*';
+
interface ESDataStreamInfo {
name: string;
timestamp_field: {
@@ -54,12 +55,8 @@ export const getListHandler: RequestHandler = async (context, request, response)
try {
// Get matching data streams, their stats, and package SOs
const [
- {
- body: { data_streams: dataStreamsInfo },
- },
- {
- body: { data_streams: dataStreamStats },
- },
+ { data_streams: dataStreamsInfo },
+ { data_streams: dataStreamStats },
packageSavedObjects,
] = await Promise.all([
esClient.indices.getDataStream({ name: DATA_STREAM_INDEX_PATTERN }),
@@ -134,9 +131,7 @@ export const getListHandler: RequestHandler = async (context, request, response)
};
// Query backing indices to extract data stream dataset, namespace, and type values
- const {
- body: { aggregations: dataStreamAggs },
- } = await esClient.search({
+ const { aggregations: dataStreamAggs } = await esClient.search({
index: dataStream.name,
body: {
size: 0,
diff --git a/x-pack/plugins/fleet/server/services/agent_policy.ts b/x-pack/plugins/fleet/server/services/agent_policy.ts
index cf06fc605e8de..50586badbe0c8 100644
--- a/x-pack/plugins/fleet/server/services/agent_policy.ts
+++ b/x-pack/plugins/fleet/server/services/agent_policy.ts
@@ -678,7 +678,7 @@ class AgentPolicyService {
return null;
}
- return res.body.hits.hits[0]._source;
+ return res.hits.hits[0]._source;
}
public async getFullAgentConfigMap(
diff --git a/x-pack/plugins/fleet/server/services/agents/crud.test.ts b/x-pack/plugins/fleet/server/services/agents/crud.test.ts
index 01b7d21ef2809..6ae8fbd471238 100644
--- a/x-pack/plugins/fleet/server/services/agents/crud.test.ts
+++ b/x-pack/plugins/fleet/server/services/agents/crud.test.ts
@@ -26,19 +26,19 @@ describe('Agents CRUD test', () => {
search: searchMock,
} as unknown as ElasticsearchClient;
});
+
function getEsResponse(ids: string[], total: number) {
return {
- body: {
- hits: {
- total: { value: total },
- hits: ids.map((id: string) => ({
- _id: id,
- _source: {},
- })),
- },
+ hits: {
+ total: { value: total },
+ hits: ids.map((id: string) => ({
+ _id: id,
+ _source: {},
+ })),
},
};
}
+
it('should return upgradeable on first page', async () => {
searchMock
.mockImplementationOnce(() => Promise.resolve(getEsResponse(['1', '2', '3', '4', '5'], 7)))
diff --git a/x-pack/plugins/fleet/server/services/agents/crud.ts b/x-pack/plugins/fleet/server/services/agents/crud.ts
index b37073b11c2ad..426bddd1bd9b9 100644
--- a/x-pack/plugins/fleet/server/services/agents/crud.ts
+++ b/x-pack/plugins/fleet/server/services/agents/crud.ts
@@ -136,8 +136,8 @@ export async function getAgentsByKuery(
});
const res = await queryAgents((page - 1) * perPage, perPage);
- let agents = res.body.hits.hits.map(searchHitToAgent);
- let total = (res.body.hits.total as estypes.SearchTotalHits).value;
+ let agents = res.hits.hits.map(searchHitToAgent);
+ let total = (res.hits.total as estypes.SearchTotalHits).value;
// filtering for a range on the version string will not work,
// nor does filtering on a flattened field (local_metadata), so filter here
if (showUpgradeable) {
@@ -146,7 +146,7 @@ export async function getAgentsByKuery(
// if there are more than SO_SEARCH_LIMIT agents, the logic falls back to same as before
if (total < SO_SEARCH_LIMIT) {
const response = await queryAgents(0, SO_SEARCH_LIMIT);
- agents = response.body.hits.hits
+ agents = response.hits.hits
.map(searchHitToAgent)
.filter((agent) => isAgentUpgradeable(agent, appContextService.getKibanaVersion()));
total = agents.length;
@@ -217,11 +217,11 @@ export async function getAgentById(esClient: ElasticsearchClient, agentId: strin
id: agentId,
});
- if (agentHit.body.found === false) {
+ if (agentHit.found === false) {
throw agentNotFoundError;
}
- return searchHitToAgent(agentHit.body);
+ return searchHitToAgent(agentHit);
} catch (err) {
if (isESClientError(err) && err.meta.statusCode === 404) {
throw agentNotFoundError;
@@ -247,7 +247,7 @@ export async function getAgentDocuments(
body: { docs: agentIds.map((_id) => ({ _id })) },
});
- return res.body.docs || [];
+ return res.docs || [];
}
export async function getAgentsById(
@@ -276,7 +276,7 @@ export async function getAgentByAccessAPIKeyId(
q: `access_api_key_id:${escapeSearchQueryPhrase(accessAPIKeyId)}`,
});
- const searchHit = res.body.hits.hits[0];
+ const searchHit = res.hits.hits[0];
const agent = searchHit && searchHitToAgent(searchHit);
if (!searchHit || !agent) {
@@ -334,7 +334,7 @@ export async function bulkUpdateAgents(
});
return {
- items: res.body.items.map((item) => ({
+ items: res.items.map((item) => ({
id: item.update!._id as string,
success: !item.update!.error,
// @ts-expect-error it not assignable to ErrorCause
diff --git a/x-pack/plugins/fleet/server/services/agents/reassign.test.ts b/x-pack/plugins/fleet/server/services/agents/reassign.test.ts
index 71935ffa5f90c..3a25efc6d49d1 100644
--- a/x-pack/plugins/fleet/server/services/agents/reassign.test.ts
+++ b/x-pack/plugins/fleet/server/services/agents/reassign.test.ts
@@ -129,7 +129,7 @@ function createClientsMock() {
const esClientMock = elasticsearchServiceMock.createClusterClient().asInternalUser;
// @ts-expect-error
- esClientMock.mget.mockImplementation(async () => {
+ esClientMock.mget.mockResponseImplementation(() => {
return {
body: {
docs: [agentInHostedDoc, agentInRegularDoc, agentInHostedDoc2],
@@ -137,7 +137,7 @@ function createClientsMock() {
};
});
// @ts-expect-error
- esClientMock.get.mockImplementation(async ({ id }) => {
+ esClientMock.get.mockResponseImplementation(({ id }) => {
switch (id) {
case agentInHostedDoc._id:
return { body: agentInHostedDoc };
@@ -147,10 +147,10 @@ function createClientsMock() {
throw new Error(`${id} not found`);
}
});
- esClientMock.bulk.mockResolvedValue({
+ esClientMock.bulk.mockResponse(
// @ts-expect-error not full interface
- body: { items: [] },
- });
+ { items: [] }
+ );
return { soClient: soClientMock, esClient: esClientMock };
}
diff --git a/x-pack/plugins/fleet/server/services/agents/status.test.ts b/x-pack/plugins/fleet/server/services/agents/status.test.ts
index 35300dfc02769..a6fd604ea0e30 100644
--- a/x-pack/plugins/fleet/server/services/agents/status.test.ts
+++ b/x-pack/plugins/fleet/server/services/agents/status.test.ts
@@ -12,26 +12,26 @@ import { getAgentStatusById } from './status';
describe('Agent status service', () => {
it('should return inactive when agent is not active', async () => {
const mockElasticsearchClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- mockElasticsearchClient.get.mockResolvedValue({
+ mockElasticsearchClient.get.mockResponse(
// @ts-expect-error not full interface
- body: {
+ {
_id: 'id',
_source: {
active: false,
local_metadata: {},
user_provided_metadata: {},
},
- },
- });
+ }
+ );
const status = await getAgentStatusById(mockElasticsearchClient, 'id');
expect(status).toEqual('inactive');
});
it('should return online when agent is active', async () => {
const mockElasticsearchClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- mockElasticsearchClient.get.mockResolvedValue({
+ mockElasticsearchClient.get.mockResponse(
// @ts-expect-error not full interface
- body: {
+ {
_id: 'id',
_source: {
active: true,
@@ -39,36 +39,35 @@ describe('Agent status service', () => {
local_metadata: {},
user_provided_metadata: {},
},
- },
- });
+ }
+ );
const status = await getAgentStatusById(mockElasticsearchClient, 'id');
expect(status).toEqual('online');
});
it('should return enrolling when agent is active but never checkin', async () => {
const mockElasticsearchClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- mockElasticsearchClient.get.mockResolvedValue({
+ mockElasticsearchClient.get.mockResponse(
// @ts-expect-error not full interface
- body: {
+ {
_id: 'id',
_source: {
active: true,
local_metadata: {},
user_provided_metadata: {},
},
- },
- });
+ }
+ );
const status = await getAgentStatusById(mockElasticsearchClient, 'id');
expect(status).toEqual('enrolling');
});
it('should return unenrolling when agent is unenrolling', async () => {
const mockElasticsearchClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- mockElasticsearchClient.get.mockResolvedValue({
+ mockElasticsearchClient.get.mockResponse(
// @ts-expect-error not full interface
- body: {
+ {
_id: 'id',
-
_source: {
active: true,
last_checkin: new Date().toISOString(),
@@ -76,8 +75,8 @@ describe('Agent status service', () => {
local_metadata: {},
user_provided_metadata: {},
},
- },
- });
+ }
+ );
const status = await getAgentStatusById(mockElasticsearchClient, 'id');
expect(status).toEqual('unenrolling');
});
diff --git a/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts b/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts
index 7f744ba6a59f4..181b517159c6f 100644
--- a/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts
+++ b/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts
@@ -263,7 +263,7 @@ function createClientMock() {
const esClientMock = elasticsearchServiceMock.createClusterClient().asInternalUser;
// @ts-expect-error
- esClientMock.get.mockImplementation(async ({ id }) => {
+ esClientMock.get.mockResponseImplementation(({ id }) => {
switch (id) {
case agentInHostedDoc._id:
return { body: agentInHostedDoc };
@@ -275,13 +275,12 @@ function createClientMock() {
throw new Error('not found');
}
});
- esClientMock.bulk.mockResolvedValue({
+ esClientMock.bulk.mockResponse(
// @ts-expect-error not full interface
- body: { items: [] },
- });
+ { items: [] }
+ );
- // @ts-expect-error
- esClientMock.mget.mockImplementation(async (params) => {
+ esClientMock.mget.mockResponseImplementation((params) => {
// @ts-expect-error
const docs = params?.body.docs.map(({ _id }) => {
switch (_id) {
diff --git a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts
index 045e6495c9675..03c9e4f979953 100644
--- a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts
+++ b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts
@@ -51,12 +51,12 @@ export async function listEnrollmentApiKeys(
});
// @ts-expect-error @elastic/elasticsearch _source is optional
- const items = res.body.hits.hits.map(esDocToEnrollmentApiKey);
+ const items = res.hits.hits.map(esDocToEnrollmentApiKey);
return {
items,
// @ts-expect-error value is number | TotalHits
- total: res.body.hits.total.value,
+ total: res.hits.total.value,
page,
perPage,
};
@@ -78,13 +78,13 @@ export async function getEnrollmentAPIKey(
id: string
): Promise {
try {
- const res = await esClient.get({
+ const body = await esClient.get({
index: ENROLLMENT_API_KEYS_INDEX,
id,
});
// @ts-expect-error esDocToEnrollmentApiKey doesn't accept optional _source
- return esDocToEnrollmentApiKey(res.body);
+ return esDocToEnrollmentApiKey(body);
} catch (e) {
if (e instanceof errors.ResponseError && e.statusCode === 404) {
throw Boom.notFound(`Enrollment api key ${id} not found`);
@@ -207,7 +207,7 @@ export async function generateEnrollmentAPIKey(
const name = providedKeyName ? `${providedKeyName} (${id})` : id;
- const { body: key } = await esClient.security
+ const key = await esClient.security
.createApiKey({
body: {
name,
@@ -264,7 +264,7 @@ export async function generateEnrollmentAPIKey(
});
return {
- id: res.body._id,
+ id: res._id,
...body,
};
}
@@ -300,7 +300,7 @@ export async function getEnrollmentAPIKeyById(esClient: ElasticsearchClient, api
});
// @ts-expect-error esDocToEnrollmentApiKey doesn't accept optional _source
- const [enrollmentAPIKey] = res.body.hits.hits.map(esDocToEnrollmentApiKey);
+ const [enrollmentAPIKey] = res.hits.hits.map(esDocToEnrollmentApiKey);
if (enrollmentAPIKey?.api_key_id !== apiKeyId) {
throw new Error(
diff --git a/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts b/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts
index 745fc1ab196bc..fedb89c1e779b 100644
--- a/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts
+++ b/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts
@@ -44,11 +44,7 @@ describe('When using the artifacts services', () => {
describe('and calling `getArtifact()`', () => {
it('should get artifact using id', async () => {
// @ts-expect-error not full interface
- esClientMock.get.mockImplementation(() => {
- return elasticsearchServiceMock.createSuccessTransportRequestPromise(
- generateArtifactEsGetSingleHitMock()
- );
- });
+ esClientMock.get.mockResponse(generateArtifactEsGetSingleHitMock());
expect(await getArtifact(esClientMock, '123')).toEqual(generateArtifactMock());
expect(esClientMock.get).toHaveBeenCalledWith({
@@ -140,11 +136,7 @@ describe('When using the artifacts services', () => {
describe('and calling `listArtifacts()`', () => {
beforeEach(() => {
- esClientMock.search.mockImplementation(() => {
- return elasticsearchServiceMock.createSuccessTransportRequestPromise(
- generateArtifactEsSearchResultHitsMock()
- );
- });
+ esClientMock.search.mockResponse(generateArtifactEsSearchResultHitsMock());
});
it('should use defaults when options is not provided', async () => {
diff --git a/x-pack/plugins/fleet/server/services/artifacts/artifacts.ts b/x-pack/plugins/fleet/server/services/artifacts/artifacts.ts
index 3a6db6fd0d04f..336a03e841266 100644
--- a/x-pack/plugins/fleet/server/services/artifacts/artifacts.ts
+++ b/x-pack/plugins/fleet/server/services/artifacts/artifacts.ts
@@ -48,7 +48,7 @@ export const getArtifact = async (
});
// @ts-expect-error @elastic/elasticsearch _source is optional
- return esSearchHitToArtifact(esData.body);
+ return esSearchHitToArtifact(esData);
} catch (e) {
if (isElasticsearchItemNotFoundError(e)) {
return;
@@ -114,11 +114,11 @@ export const listArtifacts = async (
return {
// @ts-expect-error @elastic/elasticsearch _source is optional
- items: searchResult.body.hits.hits.map((hit) => esSearchHitToArtifact(hit)),
+ items: searchResult.hits.hits.map((hit) => esSearchHitToArtifact(hit)),
page,
perPage,
// @ts-expect-error doesn't handle total as number
- total: searchResult.body.hits.total.value,
+ total: searchResult.hits.total.value,
};
} catch (e) {
throw new ArtifactsElasticsearchError(e);
diff --git a/x-pack/plugins/fleet/server/services/artifacts/client.test.ts b/x-pack/plugins/fleet/server/services/artifacts/client.test.ts
index 8b98dc861a756..d5aa2765908c1 100644
--- a/x-pack/plugins/fleet/server/services/artifacts/client.test.ts
+++ b/x-pack/plugins/fleet/server/services/artifacts/client.test.ts
@@ -29,9 +29,7 @@ describe('When using the Fleet Artifacts Client', () => {
}
// @ts-expect-error not full interface
- esClientMock.get.mockImplementation(() => {
- return elasticsearchServiceMock.createSuccessTransportRequestPromise(singleHit);
- });
+ esClientMock.get.mockResponse(singleHit);
};
beforeEach(() => {
@@ -105,11 +103,7 @@ describe('When using the Fleet Artifacts Client', () => {
describe('and calling `listArtifacts()`', () => {
beforeEach(() => {
- esClientMock.search.mockImplementation(() => {
- return elasticsearchServiceMock.createSuccessTransportRequestPromise(
- generateArtifactEsSearchResultHitsMock()
- );
- });
+ esClientMock.search.mockResponse(generateArtifactEsSearchResultHitsMock());
});
it('should retrieve list bound to packageName', async () => {
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/install.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/install.ts
index d857d7c6bc2fb..7f7e7b2ec10e9 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/install.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/install.ts
@@ -262,7 +262,7 @@ export async function ensureFleetFinalPipelineIsInstalled(
};
const res = await esClient.ingest.getPipeline(
{ id: FLEET_FINAL_PIPELINE_ID },
- esClientRequestOptions
+ { ...esClientRequestOptions, meta: true }
);
const installedVersion = res?.body[FLEET_FINAL_PIPELINE_ID]?.version;
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts
index 554105bb00a92..84dbe324891bc 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts
@@ -63,9 +63,7 @@ describe('EPM install', () => {
it('tests installPackage to use correct priority and index_patterns for data stream with dataset_is_prefix set to false', async () => {
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- esClient.indices.getIndexTemplate.mockImplementation(() =>
- elasticsearchServiceMock.createSuccessTransportRequestPromise({ index_templates: [] })
- );
+ esClient.indices.getIndexTemplate.mockResponse({ index_templates: [] });
const fields: Field[] = [];
const dataStreamDatasetIsPrefixFalse = {
@@ -104,9 +102,7 @@ describe('EPM install', () => {
it('tests installPackage to use correct priority and index_patterns for data stream with dataset_is_prefix set to true', async () => {
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- esClient.indices.getIndexTemplate.mockImplementation(() =>
- elasticsearchServiceMock.createSuccessTransportRequestPromise({ index_templates: [] })
- );
+ esClient.indices.getIndexTemplate.mockResponse({ index_templates: [] });
const fields: Field[] = [];
const dataStreamDatasetIsPrefixTrue = {
@@ -145,20 +141,19 @@ describe('EPM install', () => {
it('tests installPackage remove the aliases property if the property existed', async () => {
const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser;
- // @ts-expect-error not full interface
- esClient.indices.getIndexTemplate.mockImplementation(() =>
- elasticsearchServiceMock.createSuccessTransportRequestPromise({
- index_templates: [
- {
- name: 'metrics-package.dataset',
- index_template: {
- index_patterns: ['metrics-package.dataset-*'],
- template: { aliases: {} },
- },
+
+ esClient.indices.getIndexTemplate.mockResponse({
+ index_templates: [
+ {
+ name: 'metrics-package.dataset',
+ // @ts-expect-error not full interface
+ index_template: {
+ index_patterns: ['metrics-package.dataset-*'],
+ template: { aliases: {} },
},
- ],
- })
- );
+ },
+ ],
+ });
const fields: Field[] = [];
const dataStreamDatasetIsPrefixUnset = {
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts
index 4224ff6b01a19..6bd346f3aff89 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts
@@ -203,7 +203,9 @@ interface TemplateMapEntry {
settings: NonNullable | object;
};
}
+
type TemplateMap = Record;
+
function putComponentTemplate(
esClient: ElasticsearchClient,
logger: Logger,
@@ -300,7 +302,7 @@ async function installDataStreamComponentTemplates(params: {
() => esClient.cluster.getComponentTemplate({ name }, { ignore: [404] }),
{ logger }
);
- const hasUserSettingsTemplate = result.body.component_templates?.length === 1;
+ const hasUserSettingsTemplate = result.component_templates?.length === 1;
if (!hasUserSettingsTemplate) {
// only add if one isn't already present
const { clusterPromise } = putComponentTemplate(esClient, logger, {
@@ -323,7 +325,7 @@ export async function ensureDefaultComponentTemplate(
esClient: ElasticsearchClient,
logger: Logger
) {
- const { body: getTemplateRes } = await retryTransientEsErrors(
+ const getTemplateRes = await retryTransientEsErrors(
() =>
esClient.cluster.getComponentTemplate(
{
@@ -378,7 +380,7 @@ export async function installTemplate({
}
// Datastream now throw an error if the aliases field is present so ensure that we remove that field.
- const { body: getTemplateRes } = await retryTransientEsErrors(
+ const getTemplateRes = await retryTransientEsErrors(
() =>
esClient.indices.getIndexTemplate(
{
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.test.ts
index 927b7cb75816c..7999cfa40a11a 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.test.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.test.ts
@@ -841,10 +841,8 @@ describe('EPM template', () => {
describe('updateCurrentWriteIndices', () => {
it('update all the index matching, index template index pattern', async () => {
const esClient = elasticsearchServiceMock.createElasticsearchClient();
- esClient.indices.getDataStream.mockResolvedValue({
- body: {
- data_streams: [{ name: 'test.prefix1-default' }],
- },
+ esClient.indices.getDataStream.mockResponse({
+ data_streams: [{ name: 'test.prefix1-default' }],
} as any);
const logger = loggerMock.create();
await updateCurrentWriteIndices(esClient, logger, [
@@ -868,13 +866,11 @@ describe('EPM template', () => {
});
it('update non replicated datastream', async () => {
const esClient = elasticsearchServiceMock.createElasticsearchClient();
- esClient.indices.getDataStream.mockResolvedValue({
- body: {
- data_streams: [
- { name: 'test-non-replicated' },
- { name: 'test-replicated', replicated: true },
- ],
- },
+ esClient.indices.getDataStream.mockResponse({
+ data_streams: [
+ { name: 'test-non-replicated' },
+ { name: 'test-replicated', replicated: true },
+ ],
} as any);
const logger = loggerMock.create();
await updateCurrentWriteIndices(esClient, logger, [
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts
index 1988be042a235..a144663546ef3 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts
@@ -470,7 +470,7 @@ const getDataStreams = async (
): Promise => {
const { indexTemplate } = template;
- const { body } = await esClient.indices.getDataStream({
+ const body = await esClient.indices.getDataStream({
name: indexTemplate.index_patterns.join(','),
});
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/remove.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/remove.ts
index 39681401ac955..6a2284e0df742 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/remove.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/remove.ts
@@ -28,17 +28,8 @@ export const deleteTransforms = async (esClient: ElasticsearchClient, transformI
}
await Promise.all(
transformIds.map(async (transformId) => {
- interface TransformResponse {
- count: number;
- transforms?: Array<{
- dest: {
- index: string;
- };
- }>;
- }
-
// get the index the transform
- const { body: transformResponse } = await esClient.transform.getTransform(
+ const transformResponse = await esClient.transform.getTransform(
{ transform_id: transformId },
{ ignore: [404] }
);
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts
index 144bd2240aa01..879c7614fedbf 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts
@@ -19,8 +19,7 @@ jest.mock('./common', () => {
});
import { errors } from '@elastic/elasticsearch';
-import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
-import type { ElasticsearchClient, SavedObject, SavedObjectsClientContract } from 'kibana/server';
+import type { SavedObject, SavedObjectsClientContract } from 'kibana/server';
import { loggerMock } from '@kbn/logging-mocks';
import { ElasticsearchAssetType } from '../../../../types';
@@ -38,7 +37,7 @@ import { installTransform } from './install';
import { getAsset } from './common';
describe('test transform install', () => {
- let esClient: DeeplyMockedKeys;
+ let esClient: ReturnType;
let savedObjectsClient: jest.Mocked;
beforeEach(() => {
appContextService.start(createAppContextStartContractMock());
@@ -104,18 +103,16 @@ describe('test transform install', () => {
} as unknown as SavedObject)
);
- esClient.transform.getTransform.mockReturnValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- count: 1,
- transforms: [
- {
- dest: {
- index: 'index',
- },
+ esClient.transform.getTransform.mockResponseOnce({
+ count: 1,
+ transforms: [
+ {
+ dest: {
+ index: 'index',
},
- ],
- })
- );
+ },
+ ],
+ });
await installTransform(
{
@@ -394,18 +391,16 @@ describe('test transform install', () => {
} as unknown as SavedObject)
);
- esClient.transform.getTransform.mockReturnValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- count: 1,
- transforms: [
- {
- dest: {
- index: 'index',
- },
+ esClient.transform.getTransform.mockResponseOnce({
+ count: 1,
+ transforms: [
+ {
+ dest: {
+ index: 'index',
},
- ],
- })
- );
+ },
+ ],
+ });
await installTransform(
{
diff --git a/x-pack/plugins/fleet/server/services/fleet_server/index.ts b/x-pack/plugins/fleet/server/services/fleet_server/index.ts
index 55b0fb0dff225..0ac47df1bfdaf 100644
--- a/x-pack/plugins/fleet/server/services/fleet_server/index.ts
+++ b/x-pack/plugins/fleet/server/services/fleet_server/index.ts
@@ -19,5 +19,5 @@ export async function hasFleetServers(esClient: ElasticsearchClient) {
});
// @ts-expect-error value is number | TotalHits
- return res.body.hits.total.value > 0;
+ return res.hits.total.value > 0;
}
diff --git a/x-pack/plugins/fleet/server/telemetry/sender.ts b/x-pack/plugins/fleet/server/telemetry/sender.ts
index 2377f5e016deb..47f8a90f6cd68 100644
--- a/x-pack/plugins/fleet/server/telemetry/sender.ts
+++ b/x-pack/plugins/fleet/server/telemetry/sender.ts
@@ -110,8 +110,7 @@ export class TelemetryEventsSender {
throw Error('elasticsearch client is unavailable: cannot retrieve cluster infomation');
}
- const { body } = await this.esClient.info();
- return body;
+ return await this.esClient.info();
}
public async sendEvents(
diff --git a/x-pack/plugins/graph/server/routes/explore.ts b/x-pack/plugins/graph/server/routes/explore.ts
index 7109eee3b9111..6318d8574c397 100644
--- a/x-pack/plugins/graph/server/routes/explore.ts
+++ b/x-pack/plugins/graph/server/routes/explore.ts
@@ -49,13 +49,11 @@ export function registerExploreRoute({
try {
return response.ok({
body: {
- resp: (
- await esClient.asCurrentUser.transport.request({
- path: '/' + encodeURIComponent(request.body.index) + '/_graph/explore',
- body: request.body.query,
- method: 'POST',
- })
- ).body,
+ resp: await esClient.asCurrentUser.transport.request({
+ path: '/' + encodeURIComponent(request.body.index) + '/_graph/explore',
+ body: request.body.query,
+ method: 'POST',
+ }),
},
});
} catch (error) {
diff --git a/x-pack/plugins/graph/server/routes/search.ts b/x-pack/plugins/graph/server/routes/search.ts
index 92f3d7a02b072..ba169bf291751 100644
--- a/x-pack/plugins/graph/server/routes/search.ts
+++ b/x-pack/plugins/graph/server/routes/search.ts
@@ -44,14 +44,12 @@ export function registerSearchRoute({
try {
return response.ok({
body: {
- resp: (
- await esClient.asCurrentUser.search({
- index: request.body.index,
- body: request.body.body,
- track_total_hits: true,
- ...(includeFrozen ? { ignore_throttled: false } : {}),
- })
- ).body,
+ resp: await esClient.asCurrentUser.search({
+ index: request.body.index,
+ body: request.body.body,
+ track_total_hits: true,
+ ...(includeFrozen ? { ignore_throttled: false } : {}),
+ }),
},
});
} catch (error) {
diff --git a/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts b/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts
index 1f2927436d4ae..fb20812f3307e 100644
--- a/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts
+++ b/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts
@@ -39,9 +39,7 @@ export function registerGrokSimulateRoute(framework: KibanaFramework) {
await requestContext.core.elasticsearch.client.asCurrentUser.ingest.simulate({
body: grokdebuggerRequest.upstreamJSON,
});
- const grokdebuggerResponse = GrokdebuggerResponse.fromUpstreamJSON(
- simulateResponseFromES.body
- );
+ const grokdebuggerResponse = GrokdebuggerResponse.fromUpstreamJSON(simulateResponseFromES);
return response.ok({
body: grokdebuggerResponse,
});
diff --git a/x-pack/plugins/index_lifecycle_management/server/plugin.ts b/x-pack/plugins/index_lifecycle_management/server/plugin.ts
index 08b1033371ad5..e8f675ea7e674 100644
--- a/x-pack/plugins/index_lifecycle_management/server/plugin.ts
+++ b/x-pack/plugins/index_lifecycle_management/server/plugin.ts
@@ -26,9 +26,7 @@ const indexLifecycleDataEnricher = async (
return [];
}
- const {
- body: { indices: ilmIndicesData },
- } = await client.asCurrentUser.ilm.explainLifecycle({
+ const { indices: ilmIndicesData } = await client.asCurrentUser.ilm.explainLifecycle({
index: '*',
});
// @ts-expect-error IndexLifecyclePolicy is not compatible with IlmExplainLifecycleResponse
@@ -100,5 +98,6 @@ export class IndexLifecycleManagementServerPlugin implements Plugin {
const policyEntry = policiesMap[lifecycleName];
@@ -50,6 +51,7 @@ async function fetchPolicies(client: ElasticsearchClient): Promise {
const response = await client.indices.getTemplate({ name: templateName });
- return response.body[templateName];
+ return response[templateName];
}
async function getIndexTemplate(
@@ -39,7 +39,7 @@ async function getIndexTemplate(
options
);
- const { index_templates: templates } = response.body as {
+ const { index_templates: templates } = response as {
index_templates: TemplateFromEs[];
};
return templates.find((template) => template.name === templateName)?.index_template;
diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts
index 34a1bac2c4fd9..11811c7b7d26c 100644
--- a/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts
+++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts
@@ -74,7 +74,7 @@ async function fetchTemplates(
const response = isLegacy
? await client.indices.getTemplate({}, options)
: await client.indices.getIndexTemplate({}, options);
- return response.body;
+ return response;
}
const querySchema = schema.object({
diff --git a/x-pack/plugins/index_management/server/lib/fetch_indices.test.ts b/x-pack/plugins/index_management/server/lib/fetch_indices.test.ts
index 900e3ecc32501..570e609219263 100644
--- a/x-pack/plugins/index_management/server/lib/fetch_indices.test.ts
+++ b/x-pack/plugins/index_management/server/lib/fetch_indices.test.ts
@@ -33,15 +33,11 @@ describe('[Index management API Routes] fetch indices lib function', () => {
test('regular index', async () => {
getIndices.mockResolvedValue({
- body: {
- regular_index: createTestIndexState(),
- },
+ regular_index: createTestIndexState(),
});
getIndicesStats.mockResolvedValue({
- body: {
- indices: {
- regular_index: createTestIndexStats({ uuid: 'regular_index' }),
- },
+ indices: {
+ regular_index: createTestIndexStats({ uuid: 'regular_index' }),
},
});
@@ -51,17 +47,13 @@ describe('[Index management API Routes] fetch indices lib function', () => {
});
test('index with aliases', async () => {
getIndices.mockResolvedValue({
- body: {
- index_with_aliases: createTestIndexState({
- aliases: { test_alias: {}, another_alias: {} },
- }),
- },
+ index_with_aliases: createTestIndexState({
+ aliases: { test_alias: {}, another_alias: {} },
+ }),
});
getIndicesStats.mockResolvedValue({
- body: {
- indices: {
- index_with_aliases: createTestIndexStats({ uuid: 'index_with_aliases' }),
- },
+ indices: {
+ index_with_aliases: createTestIndexStats({ uuid: 'index_with_aliases' }),
},
});
@@ -77,18 +69,14 @@ describe('[Index management API Routes] fetch indices lib function', () => {
});
test('frozen index', async () => {
getIndices.mockResolvedValue({
- body: {
- frozen_index: createTestIndexState({
- // @ts-expect-error
- settings: { index: { number_of_shards: 1, number_of_replicas: 1, frozen: 'true' } },
- }),
- },
+ frozen_index: createTestIndexState({
+ // @ts-expect-error
+ settings: { index: { number_of_shards: 1, number_of_replicas: 1, frozen: 'true' } },
+ }),
});
getIndicesStats.mockResolvedValue({
- body: {
- indices: {
- frozen_index: createTestIndexStats({ uuid: 'frozen_index' }),
- },
+ indices: {
+ frozen_index: createTestIndexStats({ uuid: 'frozen_index' }),
},
});
@@ -104,17 +92,13 @@ describe('[Index management API Routes] fetch indices lib function', () => {
});
test('hidden index', async () => {
getIndices.mockResolvedValue({
- body: {
- hidden_index: createTestIndexState({
- settings: { index: { number_of_shards: 1, number_of_replicas: 1, hidden: 'true' } },
- }),
- },
+ hidden_index: createTestIndexState({
+ settings: { index: { number_of_shards: 1, number_of_replicas: 1, hidden: 'true' } },
+ }),
});
getIndicesStats.mockResolvedValue({
- body: {
- indices: {
- hidden_index: createTestIndexStats({ uuid: 'hidden_index' }),
- },
+ indices: {
+ hidden_index: createTestIndexStats({ uuid: 'hidden_index' }),
},
});
@@ -130,17 +114,13 @@ describe('[Index management API Routes] fetch indices lib function', () => {
});
test('data stream index', async () => {
getIndices.mockResolvedValue({
- body: {
- data_stream_index: createTestIndexState({
- data_stream: 'test_data_stream',
- }),
- },
+ data_stream_index: createTestIndexState({
+ data_stream: 'test_data_stream',
+ }),
});
getIndicesStats.mockResolvedValue({
- body: {
- indices: {
- data_stream_index: createTestIndexStats({ uuid: 'data_stream_index' }),
- },
+ indices: {
+ data_stream_index: createTestIndexStats({ uuid: 'data_stream_index' }),
},
});
@@ -156,17 +136,13 @@ describe('[Index management API Routes] fetch indices lib function', () => {
});
test('index missing in stats call', async () => {
getIndices.mockResolvedValue({
- body: {
- index_missing_stats: createTestIndexState(),
- },
+ index_missing_stats: createTestIndexState(),
});
// simulates when an index has been deleted after get indices call
// deleted index won't be present in the indices stats call response
getIndicesStats.mockResolvedValue({
- body: {
- indices: {
- some_other_index: createTestIndexStats({ uuid: 'some_other_index' }),
- },
+ indices: {
+ some_other_index: createTestIndexStats({ uuid: 'some_other_index' }),
},
});
await expect(router.runRequest(mockRequest)).resolves.toEqual({
diff --git a/x-pack/plugins/index_management/server/lib/fetch_indices.ts b/x-pack/plugins/index_management/server/lib/fetch_indices.ts
index f4b39784dde22..9e8a8b23a7d9d 100644
--- a/x-pack/plugins/index_management/server/lib/fetch_indices.ts
+++ b/x-pack/plugins/index_management/server/lib/fetch_indices.ts
@@ -17,7 +17,7 @@ async function fetchIndicesCall(
const indexNamesString = indexNames && indexNames.length ? indexNames.join(',') : '*';
// This call retrieves alias and settings (incl. hidden status) information about indices
- const { body: indices } = await client.asCurrentUser.indices.get({
+ const indices = await client.asCurrentUser.indices.get({
index: indexNamesString,
expand_wildcards: ['hidden', 'all'],
// only get specified index properties from ES to keep the response under 536MB
@@ -39,9 +39,7 @@ async function fetchIndicesCall(
return [];
}
- const {
- body: { indices: indicesStats = {} },
- } = await client.asCurrentUser.indices.stats({
+ const { indices: indicesStats = {} } = await client.asCurrentUser.indices.stats({
index: indexNamesString,
expand_wildcards: ['hidden', 'all'],
forbid_closed_indices: false,
diff --git a/x-pack/plugins/index_management/server/lib/get_managed_templates.ts b/x-pack/plugins/index_management/server/lib/get_managed_templates.ts
index 8e60044dc4951..c224799a8c35c 100644
--- a/x-pack/plugins/index_management/server/lib/get_managed_templates.ts
+++ b/x-pack/plugins/index_management/server/lib/get_managed_templates.ts
@@ -13,9 +13,7 @@ export const getCloudManagedTemplatePrefix = async (
client: IScopedClusterClient
): Promise => {
try {
- const {
- body: { persistent, transient, defaults },
- } = await client.asCurrentUser.cluster.getSettings({
+ const { persistent, transient, defaults } = await client.asCurrentUser.cluster.getSettings({
filter_path: '*.*managed_index_templates',
flat_settings: true,
include_defaults: true,
diff --git a/x-pack/plugins/index_management/server/routes/api/component_templates/register_create_route.ts b/x-pack/plugins/index_management/server/routes/api/component_templates/register_create_route.ts
index b4683f1b8cb14..296dcd726e52a 100644
--- a/x-pack/plugins/index_management/server/routes/api/component_templates/register_create_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/component_templates/register_create_route.ts
@@ -32,11 +32,10 @@ export const registerCreateRoute = ({
try {
// Check that a component template with the same name doesn't already exist
- const {
- body: { component_templates: componentTemplates },
- } = await client.asCurrentUser.cluster.getComponentTemplate({
- name,
- });
+ const { component_templates: componentTemplates } =
+ await client.asCurrentUser.cluster.getComponentTemplate({
+ name,
+ });
if (componentTemplates.length) {
return response.conflict({
@@ -55,7 +54,7 @@ export const registerCreateRoute = ({
}
try {
- const { body: responseBody } = await client.asCurrentUser.cluster.putComponentTemplate({
+ const responseBody = await client.asCurrentUser.cluster.putComponentTemplate({
name,
// @ts-expect-error ComponentTemplateSerialized conflicts with @elastic/elasticsearch ClusterPutComponentTemplateRequest
body: serializedComponentTemplate,
diff --git a/x-pack/plugins/index_management/server/routes/api/component_templates/register_get_route.ts b/x-pack/plugins/index_management/server/routes/api/component_templates/register_get_route.ts
index a77aa90c52f73..039eb24f4d9d6 100644
--- a/x-pack/plugins/index_management/server/routes/api/component_templates/register_get_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/component_templates/register_get_route.ts
@@ -27,13 +27,11 @@ export function registerGetAllRoute({ router, lib: { handleEsError } }: RouteDep
const { client } = context.core.elasticsearch;
try {
- const {
- body: { component_templates: componentTemplates },
- } = await client.asCurrentUser.cluster.getComponentTemplate();
+ const { component_templates: componentTemplates } =
+ await client.asCurrentUser.cluster.getComponentTemplate();
- const {
- body: { index_templates: indexTemplates },
- } = await client.asCurrentUser.indices.getIndexTemplate();
+ const { index_templates: indexTemplates } =
+ await client.asCurrentUser.indices.getIndexTemplate();
const body = componentTemplates.map((componentTemplate: ComponentTemplateFromEs) => {
const deserializedComponentTemplateListItem = deserializeComponentTemplateList(
@@ -63,15 +61,13 @@ export function registerGetAllRoute({ router, lib: { handleEsError } }: RouteDep
const { name } = request.params;
try {
- const {
- body: { component_templates: componentTemplates },
- } = await client.asCurrentUser.cluster.getComponentTemplate({
- name,
- });
+ const { component_templates: componentTemplates } =
+ await client.asCurrentUser.cluster.getComponentTemplate({
+ name,
+ });
- const {
- body: { index_templates: indexTemplates },
- } = await client.asCurrentUser.indices.getIndexTemplate();
+ const { index_templates: indexTemplates } =
+ await client.asCurrentUser.indices.getIndexTemplate();
return response.ok({
body: deserializeComponentTemplate(componentTemplates[0], indexTemplates),
diff --git a/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts b/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts
index 2c5070ab846ad..dd37ad56ea4b4 100644
--- a/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts
+++ b/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts
@@ -58,13 +58,11 @@ describe('GET privileges', () => {
it('should return the correct response when a user has privileges', async () => {
const privilegesResponseMock = {
- body: {
- username: 'elastic',
- has_all_requested: true,
- cluster: { manage_index_templates: true },
- index: {},
- application: {},
- },
+ username: 'elastic',
+ has_all_requested: true,
+ cluster: { manage_index_templates: true },
+ index: {},
+ application: {},
};
const routeContextMock = mockRouteContext({
@@ -84,13 +82,11 @@ describe('GET privileges', () => {
it('should return the correct response when a user does not have privileges', async () => {
const privilegesResponseMock = {
- body: {
- username: 'elastic',
- has_all_requested: false,
- cluster: { manage_index_templates: false },
- index: {},
- application: {},
- },
+ username: 'elastic',
+ has_all_requested: false,
+ cluster: { manage_index_templates: false },
+ index: {},
+ application: {},
};
const routeContextMock = mockRouteContext({
diff --git a/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.ts b/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.ts
index 327e6421525c6..b99e16f7eb1f2 100644
--- a/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.ts
@@ -43,13 +43,12 @@ export const registerPrivilegesRoute = ({
const { client } = context.core.elasticsearch;
try {
- const {
- body: { has_all_requested: hasAllPrivileges, cluster },
- } = await client.asCurrentUser.security.hasPrivileges({
- body: {
- cluster: ['manage_index_templates'],
- },
- });
+ const { has_all_requested: hasAllPrivileges, cluster } =
+ await client.asCurrentUser.security.hasPrivileges({
+ body: {
+ cluster: ['manage_index_templates'],
+ },
+ });
if (!hasAllPrivileges) {
privilegesResult.missingPrivileges.cluster = extractMissingPrivileges(cluster);
diff --git a/x-pack/plugins/index_management/server/routes/api/component_templates/register_update_route.ts b/x-pack/plugins/index_management/server/routes/api/component_templates/register_update_route.ts
index c2235b9eb85ab..97d7c52dde044 100644
--- a/x-pack/plugins/index_management/server/routes/api/component_templates/register_update_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/component_templates/register_update_route.ts
@@ -37,7 +37,7 @@ export const registerUpdateRoute = ({
// Verify component exists; ES will throw 404 if not
await client.asCurrentUser.cluster.getComponentTemplate({ name });
- const { body: responseBody } = await client.asCurrentUser.cluster.putComponentTemplate({
+ const responseBody = await client.asCurrentUser.cluster.putComponentTemplate({
name,
body: {
template: template as estypes.IndicesIndexState,
diff --git a/x-pack/plugins/index_management/server/routes/api/data_streams/register_get_route.ts b/x-pack/plugins/index_management/server/routes/api/data_streams/register_get_route.ts
index 87eecfbfbbbad..4c44d1a8212f9 100644
--- a/x-pack/plugins/index_management/server/routes/api/data_streams/register_get_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/data_streams/register_get_route.ts
@@ -108,24 +108,20 @@ export function registerGetAllRoute({ router, lib: { handleEsError }, config }:
const includeStats = (request.query as TypeOf).includeStats === 'true';
try {
- const {
- body: { data_streams: dataStreams },
- } = await getDataStreams(client);
+ const { data_streams: dataStreams } = await getDataStreams(client);
let dataStreamsStats;
let dataStreamsPrivileges;
if (includeStats) {
- ({
- body: { data_streams: dataStreamsStats },
- } = await getDataStreamsStats(client));
+ ({ data_streams: dataStreamsStats } = await getDataStreamsStats(client));
}
if (config.isSecurityEnabled() && dataStreams.length > 0) {
- ({ body: dataStreamsPrivileges } = await getDataStreamsPrivileges(
+ dataStreamsPrivileges = await getDataStreamsPrivileges(
client,
dataStreams.map((dataStream) => dataStream.name)
- ));
+ );
}
const enhancedDataStreams = enhanceDataStreams({
@@ -158,21 +154,13 @@ export function registerGetOneRoute({ router, lib: { handleEsError }, config }:
const { name } = request.params as TypeOf;
const { client } = context.core.elasticsearch;
try {
- const [
- {
- body: { data_streams: dataStreams },
- },
- {
- body: { data_streams: dataStreamsStats },
- },
- ] = await Promise.all([getDataStreams(client, name), getDataStreamsStats(client, name)]);
+ const [{ data_streams: dataStreams }, { data_streams: dataStreamsStats }] =
+ await Promise.all([getDataStreams(client, name), getDataStreamsStats(client, name)]);
if (dataStreams[0]) {
let dataStreamsPrivileges;
if (config.isSecurityEnabled()) {
- ({ body: dataStreamsPrivileges } = await getDataStreamsPrivileges(client, [
- dataStreams[0].name,
- ]));
+ dataStreamsPrivileges = await getDataStreamsPrivileges(client, [dataStreams[0].name]);
}
const enhancedDataStreams = enhanceDataStreams({
diff --git a/x-pack/plugins/index_management/server/routes/api/mapping/register_mapping_route.ts b/x-pack/plugins/index_management/server/routes/api/mapping/register_mapping_route.ts
index 1bb54798c6804..cef20539f9403 100644
--- a/x-pack/plugins/index_management/server/routes/api/mapping/register_mapping_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/mapping/register_mapping_route.ts
@@ -33,7 +33,7 @@ export function registerMappingRoute({ router, lib: { handleEsError } }: RouteDe
};
try {
- const { body: hit } = await client.asCurrentUser.indices.getMapping(params);
+ const hit = await client.asCurrentUser.indices.getMapping(params);
const responseBody = formatHit(hit, indexName);
return response.ok({ body: responseBody });
} catch (error) {
diff --git a/x-pack/plugins/index_management/server/routes/api/nodes/register_nodes_route.test.ts b/x-pack/plugins/index_management/server/routes/api/nodes/register_nodes_route.test.ts
index aa3591d2d064f..fb104b3dc868f 100644
--- a/x-pack/plugins/index_management/server/routes/api/nodes/register_nodes_route.test.ts
+++ b/x-pack/plugins/index_management/server/routes/api/nodes/register_nodes_route.test.ts
@@ -29,14 +29,12 @@ describe('[Index management API Routes] Nodes info', () => {
// Mock the response from the ES client ('nodes.info()')
getNodesInfo.mockResolvedValue({
- body: {
- nodes: {
- node1: {
- plugins: [{ name: 'plugin-1' }, { name: 'plugin-2' }],
- },
- node2: {
- plugins: [{ name: 'plugin-1' }, { name: 'plugin-3' }],
- },
+ nodes: {
+ node1: {
+ plugins: [{ name: 'plugin-1' }, { name: 'plugin-2' }],
+ },
+ node2: {
+ plugins: [{ name: 'plugin-1' }, { name: 'plugin-3' }],
},
},
});
diff --git a/x-pack/plugins/index_management/server/routes/api/nodes/register_nodes_route.ts b/x-pack/plugins/index_management/server/routes/api/nodes/register_nodes_route.ts
index f2cfae32d00fe..5c9751c8506cf 100644
--- a/x-pack/plugins/index_management/server/routes/api/nodes/register_nodes_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/nodes/register_nodes_route.ts
@@ -16,7 +16,7 @@ export function registerNodesRoute({ router, lib: { handleEsError } }: RouteDepe
const { client } = context.core.elasticsearch;
try {
- const { body } = await client.asCurrentUser.nodes.info();
+ const body = await client.asCurrentUser.nodes.info();
const plugins: Set = Object.values(body.nodes).reduce((acc, nodeInfo) => {
nodeInfo.plugins?.forEach(({ name }) => {
acc.add(name);
diff --git a/x-pack/plugins/index_management/server/routes/api/settings/register_load_route.ts b/x-pack/plugins/index_management/server/routes/api/settings/register_load_route.ts
index b942f1976b2fd..ceb59916811d8 100644
--- a/x-pack/plugins/index_management/server/routes/api/settings/register_load_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/settings/register_load_route.ts
@@ -36,7 +36,7 @@ export function registerLoadRoute({ router, lib: { handleEsError } }: RouteDepen
};
try {
- const { body: hit } = await client.asCurrentUser.indices.getSettings(params);
+ const hit = await client.asCurrentUser.indices.getSettings(params);
return response.ok({ body: formatHit(hit) });
} catch (error) {
return handleEsError({ error, response });
diff --git a/x-pack/plugins/index_management/server/routes/api/settings/register_update_route.ts b/x-pack/plugins/index_management/server/routes/api/settings/register_update_route.ts
index 4021af3b75014..b7a38cb04782e 100644
--- a/x-pack/plugins/index_management/server/routes/api/settings/register_update_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/settings/register_update_route.ts
@@ -34,7 +34,7 @@ export function registerUpdateRoute({ router, lib: { handleEsError } }: RouteDep
};
try {
- const { body: responseBody } = await client.asCurrentUser.indices.putSettings(params);
+ const responseBody = await client.asCurrentUser.indices.putSettings(params);
return response.ok({ body: responseBody });
} catch (error) {
return handleEsError({ error, response });
diff --git a/x-pack/plugins/index_management/server/routes/api/stats/register_stats_route.ts b/x-pack/plugins/index_management/server/routes/api/stats/register_stats_route.ts
index 6e74523dbd197..f178cc8ace6bc 100644
--- a/x-pack/plugins/index_management/server/routes/api/stats/register_stats_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/stats/register_stats_route.ts
@@ -41,7 +41,7 @@ export function registerStatsRoute({ router, lib: { handleEsError } }: RouteDepe
};
try {
- const { body: hit } = await client.asCurrentUser.indices.stats(params);
+ const hit = await client.asCurrentUser.indices.stats(params);
return response.ok({ body: formatHit(hit, indexName) });
} catch (error) {
diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_create_route.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_create_route.ts
index 21be254eb9d73..20a3e1e97dd6c 100644
--- a/x-pack/plugins/index_management/server/routes/api/templates/register_create_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/templates/register_create_route.ts
@@ -28,7 +28,7 @@ export function registerCreateRoute({ router, lib: { handleEsError } }: RouteDep
} = template;
// Check that template with the same name doesn't already exist
- const { body: templateExists } = await doesTemplateExist({
+ const templateExists = await doesTemplateExist({
name: template.name,
client,
isLegacy,
@@ -48,7 +48,7 @@ export function registerCreateRoute({ router, lib: { handleEsError } }: RouteDep
}
// Otherwise create new index template
- const { body: responseBody } = await saveTemplate({ template, client, isLegacy });
+ const responseBody = await saveTemplate({ template, client, isLegacy });
return response.ok({ body: responseBody });
} catch (error) {
diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_get_routes.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_get_routes.ts
index 9d0b7302b5587..8eedcee590fd5 100644
--- a/x-pack/plugins/index_management/server/routes/api/templates/register_get_routes.ts
+++ b/x-pack/plugins/index_management/server/routes/api/templates/register_get_routes.ts
@@ -26,10 +26,9 @@ export function registerGetAllRoute({ router, lib: { handleEsError } }: RouteDep
try {
const cloudManagedTemplatePrefix = await getCloudManagedTemplatePrefix(client);
- const { body: legacyTemplatesEs } = await client.asCurrentUser.indices.getTemplate();
- const {
- body: { index_templates: templatesEs },
- } = await client.asCurrentUser.indices.getIndexTemplate();
+ const legacyTemplatesEs = await client.asCurrentUser.indices.getTemplate();
+ const { index_templates: templatesEs } =
+ await client.asCurrentUser.indices.getIndexTemplate();
const legacyTemplates = deserializeLegacyTemplateList(
legacyTemplatesEs,
@@ -74,7 +73,7 @@ export function registerGetOneRoute({ router, lib: { handleEsError } }: RouteDep
const cloudManagedTemplatePrefix = await getCloudManagedTemplatePrefix(client);
if (isLegacy) {
- const { body: indexTemplateByName } = await client.asCurrentUser.indices.getTemplate({
+ const indexTemplateByName = await client.asCurrentUser.indices.getTemplate({
name,
});
@@ -87,9 +86,8 @@ export function registerGetOneRoute({ router, lib: { handleEsError } }: RouteDep
});
}
} else {
- const {
- body: { index_templates: indexTemplates },
- } = await client.asCurrentUser.indices.getIndexTemplate({ name });
+ const { index_templates: indexTemplates } =
+ await client.asCurrentUser.indices.getIndexTemplate({ name });
if (indexTemplates.length > 0) {
return response.ok({
diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts
index e45d86f3e2b27..ab937fc366d4c 100644
--- a/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts
@@ -23,7 +23,7 @@ export function registerSimulateRoute({ router, lib: { handleEsError } }: RouteD
const template = request.body as TypeOf;
try {
- const { body: templatePreview } = await client.asCurrentUser.indices.simulateTemplate({
+ const templatePreview = await client.asCurrentUser.indices.simulateTemplate({
body: {
...template,
// Until ES fixes a bug on their side we need to send a fake index pattern
diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_update_route.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_update_route.ts
index 669a1fff66317..f700497e924b4 100644
--- a/x-pack/plugins/index_management/server/routes/api/templates/register_update_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/templates/register_update_route.ts
@@ -35,14 +35,14 @@ export function registerUpdateRoute({ router, lib: { handleEsError } }: RouteDep
} = template;
// Verify the template exists (ES will throw 404 if not)
- const { body: templateExists } = await doesTemplateExist({ name, client, isLegacy });
+ const templateExists = await doesTemplateExist({ name, client, isLegacy });
if (!templateExists) {
return response.notFound();
}
// Next, update index template
- const { body: responseBody } = await saveTemplate({ template, client, isLegacy });
+ const responseBody = await saveTemplate({ template, client, isLegacy });
return response.ok({ body: responseBody });
} catch (error) {
diff --git a/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts
index 0c0284e328dd3..3ed94af04031f 100644
--- a/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts
+++ b/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts
@@ -199,7 +199,7 @@ export class KibanaFramework {
} as estypes.MlGetBucketsRequest);
break;
}
- return apiResult ? (await apiResult).body : undefined;
+ return apiResult ? await apiResult : undefined;
}
public async getIndexPatternsServiceWithRequestContext(
diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/lib/get_data.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/lib/get_data.ts
index 83751087d9aff..9f8bd5674dcef 100644
--- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/lib/get_data.ts
+++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/lib/get_data.ts
@@ -84,7 +84,7 @@ export const getData = async (
filterQuery,
customMetric
);
- const { body } = await esClient.search(request);
+ const body = await esClient.search(request);
if (body.aggregations) {
return handleResponse(body.aggregations, previousNodes);
}
diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts
index f817b68b919ba..674ba977e09c0 100644
--- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts
+++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts
@@ -759,7 +759,7 @@ const getQueryMappingForComparator = (comparator: Comparator) => {
};
const getUngroupedResults = async (query: object, esClient: ElasticsearchClient) => {
- return decodeOrThrow(UngroupedSearchQueryResponseRT)((await esClient.search(query)).body);
+ return decodeOrThrow(UngroupedSearchQueryResponseRT)(await esClient.search(query));
};
const getGroupedResults = async (query: object, esClient: ElasticsearchClient) => {
@@ -770,7 +770,7 @@ const getGroupedResults = async (query: object, esClient: ElasticsearchClient) =
const queryWithAfterKey: any = { ...query };
queryWithAfterKey.body.aggregations.groups.composite.after = lastAfterKey;
const groupResponse: GroupedSearchQueryResponse = decodeOrThrow(GroupedSearchQueryResponseRT)(
- (await esClient.search(queryWithAfterKey)).body
+ await esClient.search(queryWithAfterKey)
);
compositeGroupBuckets = [
...compositeGroupBuckets,
diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_rule.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_rule.ts
index 4fbac02cff19b..744fd80134aec 100644
--- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_rule.ts
+++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_rule.ts
@@ -199,7 +199,7 @@ const getMetric: (
);
const compositeBuckets = (await getAllCompositeData(
// @ts-expect-error @elastic/elasticsearch SearchResponse.body.timeout is not required
- (body) => esClient.search({ body, index }),
+ (body) => esClient.search({ body, index }, { meta: true }),
searchBody,
bucketSelector,
afterKeyHandler
@@ -218,7 +218,7 @@ const getMetric: (
}
return groupedResults;
}
- const { body: result } = await esClient.search({
+ const result = await esClient.search({
body: searchBody,
index,
});
diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.test.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.test.ts
index 57001d8cbdb1a..1929a91d763d1 100644
--- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.test.ts
+++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.test.ts
@@ -5,8 +5,6 @@
* 2.0.
*/
-// eslint-disable-next-line @kbn/eslint/no-restricted-paths
-import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks';
import {
AlertInstanceContext as AlertContext,
AlertInstanceState as AlertState,
@@ -784,43 +782,39 @@ const services: AlertServicesMock & LifecycleAlertServices {
- const from = params?.body.query.bool.filter[0]?.range['@timestamp'].gte;
- if (params.index === 'alternatebeat-*') return mocks.changedSourceIdResponse(from);
+services.scopedClusterClient.asCurrentUser.search.mockResponseImplementation(
+ (params?: any): any => {
+ const from = params?.body.query.bool.filter[0]?.range['@timestamp'].gte;
- if (params.index === 'empty-response') return mocks.emptyMetricResponse;
+ if (params.index === 'alternatebeat-*') return { body: mocks.changedSourceIdResponse(from) };
- const metric = params?.body.query.bool.filter[1]?.exists.field;
- if (metric === 'test.metric.3') {
- return elasticsearchClientMock.createSuccessTransportRequestPromise(
- params?.body.aggs.aggregatedIntervals?.aggregations.aggregatedValueMax
- ? mocks.emptyRateResponse
- : mocks.emptyMetricResponse
- );
- }
- if (params?.body.aggs.groupings) {
- if (params?.body.aggs.groupings.composite.after) {
- return elasticsearchClientMock.createSuccessTransportRequestPromise(
- mocks.compositeEndResponse
- );
+ if (params.index === 'empty-response') return { body: mocks.emptyMetricResponse };
+
+ const metric = params?.body.query.bool.filter[1]?.exists.field;
+ if (metric === 'test.metric.3') {
+ return {
+ body: params?.body.aggs.aggregatedIntervals?.aggregations.aggregatedValueMax
+ ? mocks.emptyRateResponse
+ : mocks.emptyMetricResponse,
+ };
+ }
+ if (params?.body.aggs.groupings) {
+ if (params?.body.aggs.groupings.composite.after) {
+ return { body: mocks.compositeEndResponse };
+ }
+ if (metric === 'test.metric.2') {
+ return { body: mocks.alternateCompositeResponse(from) };
+ }
+ return { body: mocks.basicCompositeResponse(from) };
}
if (metric === 'test.metric.2') {
- return elasticsearchClientMock.createSuccessTransportRequestPromise(
- mocks.alternateCompositeResponse(from)
- );
+ return { body: mocks.alternateMetricResponse() };
}
- return elasticsearchClientMock.createSuccessTransportRequestPromise(
- mocks.basicCompositeResponse(from)
- );
+ return { body: mocks.basicMetricResponse() };
}
- if (metric === 'test.metric.2') {
- return elasticsearchClientMock.createSuccessTransportRequestPromise(
- mocks.alternateMetricResponse()
- );
- }
- return elasticsearchClientMock.createSuccessTransportRequestPromise(mocks.basicMetricResponse());
-});
+);
+
services.savedObjectsClient.get.mockImplementation(async (type: string, sourceId: string) => {
if (sourceId === 'alternate')
return {
@@ -909,7 +903,9 @@ declare global {
namespace jest {
interface Matchers {
toBeAlertAction(action?: Action): R;
+
toBeNoDataAction(action?: Action): R;
+
toBeErrorAction(action?: Action): R;
}
}
diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts
index d1d136c741876..316f868589064 100644
--- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts
+++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts
@@ -416,20 +416,18 @@ async function fetchLogEntryCategoryExamples(
const {
hits: { hits },
} = decodeOrThrow(logEntryCategoryExamplesResponseRT)(
- (
- await requestContext.core.elasticsearch.client.asCurrentUser.search(
- createLogEntryCategoryExamplesQuery(
- indices,
- runtimeMappings,
- timestampField,
- tiebreakerField,
- startTime,
- endTime,
- categoryQuery,
- exampleCount
- )
+ await requestContext.core.elasticsearch.client.asCurrentUser.search(
+ createLogEntryCategoryExamplesQuery(
+ indices,
+ runtimeMappings,
+ timestampField,
+ tiebreakerField,
+ startTime,
+ endTime,
+ categoryQuery,
+ exampleCount
)
- ).body
+ )
);
const esSearchSpan = finalizeEsSearchSpan();
diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/create.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/create.ts
index b078ca051a272..90893b2841cc0 100644
--- a/x-pack/plugins/ingest_pipelines/server/routes/api/create.ts
+++ b/x-pack/plugins/ingest_pipelines/server/routes/api/create.ts
@@ -38,7 +38,7 @@ export const registerCreateRoute = ({
try {
// Check that a pipeline with the same name doesn't already exist
- const { body: pipelineByName } = await clusterClient.asCurrentUser.ingest.getPipeline({
+ const pipelineByName = await clusterClient.asCurrentUser.ingest.getPipeline({
id: name,
});
@@ -59,7 +59,7 @@ export const registerCreateRoute = ({
}
try {
- const { body: response } = await clusterClient.asCurrentUser.ingest.putPipeline({
+ const response = await clusterClient.asCurrentUser.ingest.putPipeline({
id: name,
body: {
description,
diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/documents.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/documents.ts
index 6f7233c70dbfe..d9f27ed84f899 100644
--- a/x-pack/plugins/ingest_pipelines/server/routes/api/documents.ts
+++ b/x-pack/plugins/ingest_pipelines/server/routes/api/documents.ts
@@ -31,7 +31,7 @@ export const registerDocumentsRoute = ({
const { index, id } = req.params;
try {
- const { body: document } = await clusterClient.asCurrentUser.get({ index, id });
+ const document = await clusterClient.asCurrentUser.get({ index, id });
const { _id, _index, _source } = document;
diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/get.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/get.ts
index b512ebda5ecdb..7da2cf3e6a13a 100644
--- a/x-pack/plugins/ingest_pipelines/server/routes/api/get.ts
+++ b/x-pack/plugins/ingest_pipelines/server/routes/api/get.ts
@@ -21,7 +21,7 @@ export const registerGetRoutes = ({ router, lib: { handleEsError } }: RouteDepen
const { client: clusterClient } = ctx.core.elasticsearch;
try {
- const { body: pipelines } = await clusterClient.asCurrentUser.ingest.getPipeline();
+ const pipelines = await clusterClient.asCurrentUser.ingest.getPipeline();
return res.ok({ body: deserializePipelines(pipelines) });
} catch (error) {
@@ -48,7 +48,7 @@ export const registerGetRoutes = ({ router, lib: { handleEsError } }: RouteDepen
const { name } = req.params;
try {
- const { body: pipelines } = await clusterClient.asCurrentUser.ingest.getPipeline({
+ const pipelines = await clusterClient.asCurrentUser.ingest.getPipeline({
id: name,
});
diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts
index a2882fd7855d6..c1d79eabceb04 100644
--- a/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts
+++ b/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts
@@ -38,12 +38,11 @@ export const registerPrivilegesRoute = ({ router, config }: RouteDependencies) =
const { client: clusterClient } = ctx.core.elasticsearch;
- const {
- body: { has_all_requested: hasAllPrivileges, cluster },
- } = await clusterClient.asCurrentUser.security.hasPrivileges({
- // @ts-expect-error @elastic/elasticsearch SecurityClusterPrivilege doesn’t contain all the priviledges
- body: { cluster: APP_CLUSTER_REQUIRED_PRIVILEGES },
- });
+ const { has_all_requested: hasAllPrivileges, cluster } =
+ await clusterClient.asCurrentUser.security.hasPrivileges({
+ // @ts-expect-error @elastic/elasticsearch SecurityClusterPrivilege doesn’t contain all the priviledges
+ body: { cluster: APP_CLUSTER_REQUIRED_PRIVILEGES },
+ });
if (!hasAllPrivileges) {
privilegesResult.missingPrivileges.cluster = extractMissingPrivileges(cluster);
diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts
index c6d628294a734..9e4e894e2c7cb 100644
--- a/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts
+++ b/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts
@@ -34,7 +34,7 @@ export const registerSimulateRoute = ({
const { pipeline, documents, verbose } = req.body;
try {
- const { body: response } = await clusterClient.asCurrentUser.ingest.simulate({
+ const response = await clusterClient.asCurrentUser.ingest.simulate({
verbose,
body: {
pipeline,
diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/update.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/update.ts
index 35af1395f5e37..51983f12e6a60 100644
--- a/x-pack/plugins/ingest_pipelines/server/routes/api/update.ts
+++ b/x-pack/plugins/ingest_pipelines/server/routes/api/update.ts
@@ -39,7 +39,7 @@ export const registerUpdateRoute = ({
// Verify pipeline exists; ES will throw 404 if it doesn't
await clusterClient.asCurrentUser.ingest.getPipeline({ id: name });
- const { body: response } = await clusterClient.asCurrentUser.ingest.putPipeline({
+ const response = await clusterClient.asCurrentUser.ingest.putPipeline({
id: name,
body: {
description,
diff --git a/x-pack/plugins/lens/server/routes/existing_fields.ts b/x-pack/plugins/lens/server/routes/existing_fields.ts
index 0ee1d92d1b4ec..c5f7cfab9c245 100644
--- a/x-pack/plugins/lens/server/routes/existing_fields.ts
+++ b/x-pack/plugins/lens/server/routes/existing_fields.ts
@@ -231,7 +231,7 @@ async function fetchIndexPatternStats({
const scriptedFields = fields.filter((f) => f.isScript);
const runtimeFields = fields.filter((f) => f.runtimeField);
- const { body: result } = await client.search(
+ const result = await client.search(
{
index,
...(includeFrozen ? { ignore_throttled: false } : {}),
diff --git a/x-pack/plugins/lens/server/routes/field_stats.ts b/x-pack/plugins/lens/server/routes/field_stats.ts
index 9e48c00b9d8cb..6c1a93759030a 100644
--- a/x-pack/plugins/lens/server/routes/field_stats.ts
+++ b/x-pack/plugins/lens/server/routes/field_stats.ts
@@ -89,7 +89,7 @@ export async function initFieldsRoute(setup: CoreSetup) {
}, {} as Record);
const search = async (aggs: Record) => {
- const { body: result } = await requestClient.search({
+ const result = await requestClient.search({
index: indexPattern.title,
track_total_hits: true,
body: {
diff --git a/x-pack/plugins/lens/server/usage/saved_objects_metric_factory.ts b/x-pack/plugins/lens/server/usage/saved_objects_metric_factory.ts
index 883bd1269cd73..568b79ca47780 100644
--- a/x-pack/plugins/lens/server/usage/saved_objects_metric_factory.ts
+++ b/x-pack/plugins/lens/server/usage/saved_objects_metric_factory.ts
@@ -26,7 +26,7 @@ export function createMetricQuery(
bucketsToObject?: (arg: unknown) => Record;
}): Promise {
const esClient = await getEsClient();
- const { body: results } = await esClient.search({
+ const results = await esClient.search({
index: kibanaIndex,
body: {
query: {
diff --git a/x-pack/plugins/lens/server/usage/task.ts b/x-pack/plugins/lens/server/usage/task.ts
index 22a57017b0d1b..53af2e5551b6a 100644
--- a/x-pack/plugins/lens/server/usage/task.ts
+++ b/x-pack/plugins/lens/server/usage/task.ts
@@ -113,23 +113,23 @@ export async function getDailyEvents(
},
};
- const { body: metrics } = await esClient.search<
- ESSearchResponse
- >({
- index: kibanaIndex,
- body: {
- query: {
- bool: {
- filter: [
- { term: { type: 'lens-ui-telemetry' } },
- { range: { 'lens-ui-telemetry.date': { gte: 'now-90d/d' } } },
- ],
+ const metrics = await esClient.search>(
+ {
+ index: kibanaIndex,
+ body: {
+ query: {
+ bool: {
+ filter: [
+ { term: { type: 'lens-ui-telemetry' } },
+ { range: { 'lens-ui-telemetry.date': { gte: 'now-90d/d' } } },
+ ],
+ },
},
+ aggs,
},
- aggs,
- },
- size: 0,
- });
+ size: 0,
+ }
+ );
const byDateByType: Record> = {};
const suggestionsByDate: Record> = {};
diff --git a/x-pack/plugins/license_management/server/lib/license.ts b/x-pack/plugins/license_management/server/lib/license.ts
index f23aba4c1d3ef..12f831f3d780a 100644
--- a/x-pack/plugins/license_management/server/lib/license.ts
+++ b/x-pack/plugins/license_management/server/lib/license.ts
@@ -17,7 +17,7 @@ interface PutLicenseArg {
export async function putLicense({ acknowledge, client, licensing, license }: PutLicenseArg) {
try {
- const { body: response } = await client.asCurrentUser.license.post({
+ const response = await client.asCurrentUser.license.post({
body: license,
acknowledge,
});
diff --git a/x-pack/plugins/license_management/server/lib/permissions.ts b/x-pack/plugins/license_management/server/lib/permissions.ts
index 06395fb6302b6..64ccabcd5ee68 100644
--- a/x-pack/plugins/license_management/server/lib/permissions.ts
+++ b/x-pack/plugins/license_management/server/lib/permissions.ts
@@ -21,7 +21,7 @@ export async function getPermissions({ isSecurityEnabled, client }: GetPermissio
}
try {
- const { body: response } = await client.asCurrentUser.security.hasPrivileges({
+ const response = await client.asCurrentUser.security.hasPrivileges({
body: {
cluster: ['manage'], // License management requires "manage" cluster privileges
},
diff --git a/x-pack/plugins/license_management/server/lib/start_basic.ts b/x-pack/plugins/license_management/server/lib/start_basic.ts
index e45c758b304de..8c077332f0709 100644
--- a/x-pack/plugins/license_management/server/lib/start_basic.ts
+++ b/x-pack/plugins/license_management/server/lib/start_basic.ts
@@ -16,7 +16,7 @@ interface StartBasicArg {
export async function startBasic({ acknowledge, client, licensing }: StartBasicArg) {
try {
- const { body: response } = await client.asCurrentUser.license.postStartBasic({ acknowledge });
+ const response = await client.asCurrentUser.license.postStartBasic({ acknowledge });
const { basic_was_started: basicWasStarted } = response;
if (basicWasStarted) {
await licensing.refresh();
diff --git a/x-pack/plugins/license_management/server/lib/start_trial.ts b/x-pack/plugins/license_management/server/lib/start_trial.ts
index c1558f54b39b2..dfacee52c5c75 100644
--- a/x-pack/plugins/license_management/server/lib/start_trial.ts
+++ b/x-pack/plugins/license_management/server/lib/start_trial.ts
@@ -10,7 +10,7 @@ import { LicensingPluginStart } from '../../../licensing/server';
export async function canStartTrial(client: IScopedClusterClient) {
try {
- const { body: response } = await client.asCurrentUser.license.getTrialStatus();
+ const response = await client.asCurrentUser.license.getTrialStatus();
return response.eligible_to_start_trial;
} catch (error) {
return error.body;
@@ -24,7 +24,7 @@ interface StartTrialArg {
export async function startTrial({ client, licensing }: StartTrialArg) {
try {
- const { body: response } = await client.asCurrentUser.license.postStartTrial({
+ const response = await client.asCurrentUser.license.postStartTrial({
acknowledge: true,
});
const { trial_was_started: trialWasStarted } = response;
diff --git a/x-pack/plugins/licensing/server/plugin.test.ts b/x-pack/plugins/licensing/server/plugin.test.ts
index 71a98098bb0f5..88f08a27a255f 100644
--- a/x-pack/plugins/licensing/server/plugin.test.ts
+++ b/x-pack/plugins/licensing/server/plugin.test.ts
@@ -54,9 +54,7 @@ describe('licensing plugin', () => {
const createEsClient = (response?: Record) => {
const client = elasticsearchServiceMock.createClusterClient();
if (response) {
- client.asInternalUser.xpack.info.mockReturnValue(
- elasticsearchServiceMock.createSuccessTransportRequestPromise(response as any)
- );
+ client.asInternalUser.xpack.info.mockResponse(response as any);
}
return client;
};
@@ -109,7 +107,7 @@ describe('licensing plugin', () => {
const esClient = createEsClient();
esClient.asInternalUser.xpack.info.mockImplementation(() => {
- return elasticsearchServiceMock.createSuccessTransportRequestPromise({
+ return Promise.resolve({
license: buildRawLicense({ type: types.shift() }),
features: {},
} as estypes.XpackInfoResponse);
@@ -162,12 +160,12 @@ describe('licensing plugin', () => {
esClient.asInternalUser.xpack.info.mockImplementation(() => {
i++;
if (i === 1) {
- return elasticsearchServiceMock.createErrorTransportRequestPromise(error1);
+ return Promise.reject(error1);
}
if (i === 2) {
- return elasticsearchServiceMock.createErrorTransportRequestPromise(error2);
+ return Promise.reject(error2);
}
- return elasticsearchServiceMock.createSuccessTransportRequestPromise({
+ return Promise.resolve({
license: buildRawLicense(),
features: {},
} as estypes.XpackInfoResponse);
@@ -227,7 +225,7 @@ describe('licensing plugin', () => {
const esClient = createEsClient();
esClient.asInternalUser.xpack.info.mockImplementation(() => {
- return elasticsearchServiceMock.createSuccessTransportRequestPromise({
+ return Promise.resolve({
license: buildRawLicense({ type: types.shift() }),
features: {},
} as estypes.XpackInfoResponse);
diff --git a/x-pack/plugins/licensing/server/plugin.ts b/x-pack/plugins/licensing/server/plugin.ts
index 43c8135127871..490bf0be3b5a8 100644
--- a/x-pack/plugins/licensing/server/plugin.ts
+++ b/x-pack/plugins/licensing/server/plugin.ts
@@ -177,7 +177,7 @@ export class LicensingPlugin implements Plugin): Promise => {
const client = isPromise(clusterClient) ? await clusterClient : clusterClient;
try {
- const { body: response } = await client.asInternalUser.xpack.info();
+ const response = await client.asInternalUser.xpack.info();
const normalizedLicense =
response.license && response.license.type !== 'missing'
? normalizeServerLicense(response.license)
diff --git a/x-pack/plugins/lists/server/services/items/create_list_item.test.ts b/x-pack/plugins/lists/server/services/items/create_list_item.test.ts
index d601f7f3eff45..305aa98f0e9ed 100644
--- a/x-pack/plugins/lists/server/services/items/create_list_item.test.ts
+++ b/x-pack/plugins/lists/server/services/items/create_list_item.test.ts
@@ -27,9 +27,9 @@ describe('crete_list_item', () => {
test('it returns a list item as expected with the id changed out for the elastic id', async () => {
const options = getCreateListItemOptionsMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.index.mockReturnValue(
+ esClient.index.mockResponse(
// @ts-expect-error not full response interface
- elasticsearchClientMock.createSuccessTransportRequestPromise({ _id: 'elastic-id-123' })
+ { _id: 'elastic-id-123' }
);
const listItem = await createListItem({ ...options, esClient });
const expected = getListItemResponseMock();
@@ -54,9 +54,9 @@ describe('crete_list_item', () => {
const options = getCreateListItemOptionsMock();
options.id = undefined;
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.index.mockReturnValue(
+ esClient.index.mockResponse(
// @ts-expect-error not full response interface
- elasticsearchClientMock.createSuccessTransportRequestPromise({ _id: 'elastic-id-123' })
+ { _id: 'elastic-id-123' }
);
const list = await createListItem({ ...options, esClient });
const expected = getListItemResponseMock();
diff --git a/x-pack/plugins/lists/server/services/items/create_list_item.ts b/x-pack/plugins/lists/server/services/items/create_list_item.ts
index ccdb8ab4779b6..18a9f3ebe7726 100644
--- a/x-pack/plugins/lists/server/services/items/create_list_item.ts
+++ b/x-pack/plugins/lists/server/services/items/create_list_item.ts
@@ -68,7 +68,7 @@ export const createListItem = async ({
...baseBody,
...elasticQuery,
};
- const { body: response } = await esClient.index({
+ const response = await esClient.index({
body,
id,
index: listItemIndex,
diff --git a/x-pack/plugins/lists/server/services/items/find_list_item.test.ts b/x-pack/plugins/lists/server/services/items/find_list_item.test.ts
index 098c8d20ae5ce..48625a74b9ae1 100644
--- a/x-pack/plugins/lists/server/services/items/find_list_item.test.ts
+++ b/x-pack/plugins/lists/server/services/items/find_list_item.test.ts
@@ -19,42 +19,40 @@ describe('find_list_item', () => {
test('should find a simple single list item', async () => {
const options = getFindListItemOptionsMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.count.mockReturnValue(
+ esClient.count.mockResponse(
// @ts-expect-error not full response interface
- elasticsearchClientMock.createSuccessTransportRequestPromise({ count: 1 })
+ { count: 1 }
);
- esClient.search.mockReturnValue(
- // @ts-expect-error not full response interface
- elasticsearchClientMock.createSuccessTransportRequestPromise({
- _scroll_id: '123',
- _shards: getShardMock(),
- hits: {
- hits: [
- {
- _id: 'some-list-item-id',
- _source: {
- _version: 'undefined',
- created_at: '2020-04-20T15:25:31.830Z',
- created_by: 'some user',
- date_range: '127.0.0.1',
- deserializer: undefined,
- list_id: 'some-list-id',
- meta: {},
- serializer: undefined,
- tie_breaker_id: '6a76b69d-80df-4ab2-8c3e-85f466b06a0e',
- type: 'ip',
- updated_at: '2020-04-20T15:25:31.830Z',
- updated_by: 'some user',
- },
+ esClient.search.mockResponse({
+ _scroll_id: '123',
+ _shards: getShardMock(),
+ hits: {
+ hits: [
+ // @ts-expect-error not full response interface
+ {
+ _id: 'some-list-item-id',
+ _source: {
+ _version: 'undefined',
+ created_at: '2020-04-20T15:25:31.830Z',
+ created_by: 'some user',
+ date_range: '127.0.0.1',
+ deserializer: undefined,
+ list_id: 'some-list-id',
+ meta: {},
+ serializer: undefined,
+ tie_breaker_id: '6a76b69d-80df-4ab2-8c3e-85f466b06a0e',
+ type: 'ip',
+ updated_at: '2020-04-20T15:25:31.830Z',
+ updated_by: 'some user',
},
- ],
- max_score: 0,
- total: 1,
- },
- timed_out: false,
- took: 10,
- })
- );
+ },
+ ],
+ max_score: 0,
+ total: 1,
+ },
+ timed_out: false,
+ took: 10,
+ });
const item = await findListItem({ ...options, esClient });
const expected = getFoundListItemSchemaMock();
expect(item).toEqual(expected);
@@ -63,9 +61,7 @@ describe('find_list_item', () => {
test('should return null if the list is null', async () => {
const options = getFindListItemOptionsMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(getEmptySearchListMock())
- );
+ esClient.search.mockResponse(getEmptySearchListMock());
const item = await findListItem({ ...options, esClient });
expect(item).toEqual(null);
});
diff --git a/x-pack/plugins/lists/server/services/items/find_list_item.ts b/x-pack/plugins/lists/server/services/items/find_list_item.ts
index 4ab8c11cc5b2f..459cadfe0abcf 100644
--- a/x-pack/plugins/lists/server/services/items/find_list_item.ts
+++ b/x-pack/plugins/lists/server/services/items/find_list_item.ts
@@ -74,7 +74,7 @@ export const findListItem = async ({
sortOrder,
});
- const { body: respose } = await esClient.count({
+ const respose = await esClient.count({
body: {
query,
},
@@ -86,7 +86,7 @@ export const findListItem = async ({
// Note: This typing of response = await esClient>
// is because when you pass in seq_no_primary_term: true it does a "fall through" type and you have
// to explicitly define the type .
- const { body: response } = await esClient.search({
+ const response = await esClient.search({
body: {
query,
search_after: scroll.searchAfter,
diff --git a/x-pack/plugins/lists/server/services/items/get_list_item.test.ts b/x-pack/plugins/lists/server/services/items/get_list_item.test.ts
index f6ec534a39ebb..7b867db9868d4 100644
--- a/x-pack/plugins/lists/server/services/items/get_list_item.test.ts
+++ b/x-pack/plugins/lists/server/services/items/get_list_item.test.ts
@@ -33,9 +33,7 @@ describe('get_list_item', () => {
test('it returns a list item as expected if the list item is found', async () => {
const data = getSearchListItemMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(data)
- );
+ esClient.search.mockResponse(data);
const list = await getListItem({ esClient, id: LIST_ID, listItemIndex: LIST_INDEX });
const expected = getListItemResponseMock();
expect(list).toEqual(expected);
@@ -45,9 +43,7 @@ describe('get_list_item', () => {
const data = getSearchListItemMock();
data.hits.hits = [];
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(data)
- );
+ esClient.search.mockResponse(data);
const list = await getListItem({ esClient, id: LIST_ID, listItemIndex: LIST_INDEX });
expect(list).toEqual(null);
});
@@ -89,9 +85,7 @@ describe('get_list_item', () => {
updated_by: USER,
};
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(data)
- );
+ esClient.search.mockResponse(data);
const list = await getListItem({ esClient, id: LIST_ID, listItemIndex: LIST_INDEX });
expect(list).toEqual(null);
});
diff --git a/x-pack/plugins/lists/server/services/items/get_list_item.ts b/x-pack/plugins/lists/server/services/items/get_list_item.ts
index f7b9c06349870..6a59a7f051fe1 100644
--- a/x-pack/plugins/lists/server/services/items/get_list_item.ts
+++ b/x-pack/plugins/lists/server/services/items/get_list_item.ts
@@ -26,7 +26,7 @@ export const getListItem = async ({
// Note: This typing of response = await esClient>
// is because when you pass in seq_no_primary_term: true it does a "fall through" type and you have
// to explicitly define the type .
- const { body: listItemES } = await esClient.search({
+ const listItemES = await esClient.search({
body: {
query: {
term: {
diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_by_values.test.ts b/x-pack/plugins/lists/server/services/items/get_list_item_by_values.test.ts
index f3c72794b6dd9..d57fe0e2ead92 100644
--- a/x-pack/plugins/lists/server/services/items/get_list_item_by_values.test.ts
+++ b/x-pack/plugins/lists/server/services/items/get_list_item_by_values.test.ts
@@ -37,9 +37,7 @@ describe('get_list_item_by_values', () => {
const data = getSearchListItemMock();
data.hits.hits = [];
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(data)
- );
+ esClient.search.mockResponse(data);
const listItem = await getListItemByValues({
esClient,
listId: LIST_ID,
@@ -54,9 +52,7 @@ describe('get_list_item_by_values', () => {
test('Returns transformed list item if the data exists within ES', async () => {
const data = getSearchListItemMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(data)
- );
+ esClient.search.mockResponse(data);
const listItem = await getListItemByValues({
esClient,
listId: LIST_ID,
diff --git a/x-pack/plugins/lists/server/services/items/get_list_item_by_values.ts b/x-pack/plugins/lists/server/services/items/get_list_item_by_values.ts
index 38e2283af98a7..2fb713526fce8 100644
--- a/x-pack/plugins/lists/server/services/items/get_list_item_by_values.ts
+++ b/x-pack/plugins/lists/server/services/items/get_list_item_by_values.ts
@@ -30,7 +30,7 @@ export const getListItemByValues = async ({
type,
value,
}: GetListItemByValuesOptions): Promise => {
- const { body: response } = await esClient.search({
+ const response = await esClient.search({
body: {
query: {
bool: {
diff --git a/x-pack/plugins/lists/server/services/items/search_list_item_by_values.test.ts b/x-pack/plugins/lists/server/services/items/search_list_item_by_values.test.ts
index 174a44ce16600..2511db01d1901 100644
--- a/x-pack/plugins/lists/server/services/items/search_list_item_by_values.test.ts
+++ b/x-pack/plugins/lists/server/services/items/search_list_item_by_values.test.ts
@@ -27,9 +27,7 @@ describe('search_list_item_by_values', () => {
const data = getSearchListItemMock();
data.hits.hits = [];
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(data)
- );
+ esClient.search.mockResponse(data);
const listItem = await searchListItemByValues({
esClient,
listId: LIST_ID,
@@ -45,9 +43,7 @@ describe('search_list_item_by_values', () => {
const data = getSearchListItemMock();
data.hits.hits = [];
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(data)
- );
+ esClient.search.mockResponse(data);
const listItem = await searchListItemByValues({
esClient,
listId: LIST_ID,
@@ -66,9 +62,7 @@ describe('search_list_item_by_values', () => {
test('Returns transformed list item if the data exists within ES', async () => {
const data = getSearchListItemMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(data)
- );
+ esClient.search.mockResponse(data);
const listItem = await searchListItemByValues({
esClient,
listId: LIST_ID,
diff --git a/x-pack/plugins/lists/server/services/items/search_list_item_by_values.ts b/x-pack/plugins/lists/server/services/items/search_list_item_by_values.ts
index ad4a79e69683f..fb81594137861 100644
--- a/x-pack/plugins/lists/server/services/items/search_list_item_by_values.ts
+++ b/x-pack/plugins/lists/server/services/items/search_list_item_by_values.ts
@@ -30,7 +30,7 @@ export const searchListItemByValues = async ({
type,
value,
}: SearchListItemByValuesOptions): Promise => {
- const { body: response } = await esClient.search({
+ const response = await esClient.search({
body: {
query: {
bool: {
diff --git a/x-pack/plugins/lists/server/services/items/update_list_item.test.ts b/x-pack/plugins/lists/server/services/items/update_list_item.test.ts
index 37cb665eb906e..a42253d3c1ae9 100644
--- a/x-pack/plugins/lists/server/services/items/update_list_item.test.ts
+++ b/x-pack/plugins/lists/server/services/items/update_list_item.test.ts
@@ -33,9 +33,9 @@ describe('update_list_item', () => {
(getListItem as unknown as jest.Mock).mockResolvedValueOnce(listItem);
const options = getUpdateListItemOptionsMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.update.mockReturnValue(
+ esClient.update.mockResponse(
// @ts-expect-error not full response interface
- elasticsearchClientMock.createSuccessTransportRequestPromise({ _id: 'elastic-id-123' })
+ { _id: 'elastic-id-123' }
);
const updatedList = await updateListItem({ ...options, esClient });
const expected: ListItemSchema = { ...getListItemResponseMock(), id: 'elastic-id-123' };
diff --git a/x-pack/plugins/lists/server/services/items/update_list_item.ts b/x-pack/plugins/lists/server/services/items/update_list_item.ts
index 78651bb83d73b..17e706228fb46 100644
--- a/x-pack/plugins/lists/server/services/items/update_list_item.ts
+++ b/x-pack/plugins/lists/server/services/items/update_list_item.ts
@@ -60,7 +60,7 @@ export const updateListItem = async ({
...elasticQuery,
};
- const { body: response } = await esClient.update({
+ const response = await esClient.update({
...decodeVersion(_version),
body: {
doc,
diff --git a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts
index 0918b9ebdedae..1bc0b708bdc0a 100644
--- a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts
+++ b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts
@@ -41,9 +41,7 @@ describe('write_list_items_to_stream', () => {
const firstResponse = getSearchListItemMock();
firstResponse.hits.hits = [];
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(firstResponse)
- );
+ esClient.search.mockResponse(firstResponse);
exportListItemsToStream({ ...options, esClient });
let chunks: string[] = [];
@@ -61,9 +59,7 @@ describe('write_list_items_to_stream', () => {
const options = getExportListItemsToStreamOptionsMock();
const response = getSearchListItemMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
+ esClient.search.mockResponse(response);
exportListItemsToStream({ ...options, esClient });
let chunks: string[] = [];
@@ -83,9 +79,7 @@ describe('write_list_items_to_stream', () => {
const secondResponse = getSearchListItemMock();
firstResponse.hits.hits = [...firstResponse.hits.hits, ...secondResponse.hits.hits];
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(firstResponse)
- );
+ esClient.search.mockResponse(firstResponse);
exportListItemsToStream({ ...options, esClient });
let chunks: string[] = [];
@@ -111,12 +105,8 @@ describe('write_list_items_to_stream', () => {
}
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(firstResponse)
- );
- esClient.search.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(secondResponse)
- );
+ esClient.search.mockResponseOnce(firstResponse);
+ esClient.search.mockResponseOnce(secondResponse);
exportListItemsToStream({ ...options, esClient });
let chunks: string[] = [];
@@ -136,9 +126,7 @@ describe('write_list_items_to_stream', () => {
const options = getWriteNextResponseOptions();
const listItem = getSearchListItemMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(listItem)
- );
+ esClient.search.mockResponse(listItem);
const searchAfter = await writeNextResponse({ ...options, esClient });
expect(searchAfter).toEqual(undefined);
});
@@ -148,9 +136,7 @@ describe('write_list_items_to_stream', () => {
listItem.hits.hits[0].sort = ['sort-value-1'];
const options = getWriteNextResponseOptions();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(listItem)
- );
+ esClient.search.mockResponse(listItem);
const searchAfter = await writeNextResponse({ ...options, esClient });
expect(searchAfter).toEqual(['sort-value-1']);
});
@@ -160,9 +146,7 @@ describe('write_list_items_to_stream', () => {
listItem.hits.hits = [];
const options = getWriteNextResponseOptions();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(listItem)
- );
+ esClient.search.mockResponse(listItem);
const searchAfter = await writeNextResponse({ ...options, esClient });
expect(searchAfter).toEqual(undefined);
});
diff --git a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts
index 565e8a3e196c5..1e9db1ef062f0 100644
--- a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts
+++ b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts
@@ -117,22 +117,20 @@ export const getResponse = async ({
listItemIndex,
size = SIZE,
}: GetResponseOptions): Promise> => {
- return (
- await esClient.search({
- body: {
- query: {
- term: {
- list_id: listId,
- },
+ return (await esClient.search({
+ body: {
+ query: {
+ term: {
+ list_id: listId,
},
- search_after: searchAfter,
- sort: [{ tie_breaker_id: 'asc' }],
},
- ignore_unavailable: true,
- index: listItemIndex,
- size,
- })
- ).body as unknown as estypes.SearchResponse;
+ search_after: searchAfter,
+ sort: [{ tie_breaker_id: 'asc' }],
+ },
+ ignore_unavailable: true,
+ index: listItemIndex,
+ size,
+ })) as unknown as estypes.SearchResponse;
};
export interface WriteResponseHitsToStreamOptions {
diff --git a/x-pack/plugins/lists/server/services/lists/create_list.test.ts b/x-pack/plugins/lists/server/services/lists/create_list.test.ts
index 0474f1bac2700..b2ccbd0d84fa0 100644
--- a/x-pack/plugins/lists/server/services/lists/create_list.test.ts
+++ b/x-pack/plugins/lists/server/services/lists/create_list.test.ts
@@ -28,9 +28,9 @@ describe('crete_list', () => {
test('it returns a list as expected with the id changed out for the elastic id', async () => {
const options = getCreateListOptionsMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.index.mockReturnValue(
+ esClient.index.mockResponse(
// @ts-expect-error not full response interface
- elasticsearchClientMock.createSuccessTransportRequestPromise({ _id: 'elastic-id-123' })
+ { _id: 'elastic-id-123' }
);
const list = await createList({ ...options, esClient });
const expected: ListSchema = { ...getListResponseMock(), id: 'elastic-id-123' };
@@ -44,9 +44,9 @@ describe('crete_list', () => {
serializer: '(?)',
};
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.index.mockReturnValue(
+ esClient.index.mockResponse(
// @ts-expect-error not full response interface
- elasticsearchClientMock.createSuccessTransportRequestPromise({ _id: 'elastic-id-123' })
+ { _id: 'elastic-id-123' }
);
const list = await createList({ ...options, esClient });
const expected: ListSchema = {
@@ -75,9 +75,9 @@ describe('crete_list', () => {
const options = getCreateListOptionsMock();
options.id = undefined;
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.index.mockReturnValue(
+ esClient.index.mockResponse(
// @ts-expect-error not full response interface
- elasticsearchClientMock.createSuccessTransportRequestPromise({ _id: 'elastic-id-123' })
+ { _id: 'elastic-id-123' }
);
const list = await createList({ ...options, esClient });
const expected: ListSchema = { ...getListResponseMock(), id: 'elastic-id-123' };
diff --git a/x-pack/plugins/lists/server/services/lists/create_list.ts b/x-pack/plugins/lists/server/services/lists/create_list.ts
index 521a38a51d6eb..eefcd0f41e448 100644
--- a/x-pack/plugins/lists/server/services/lists/create_list.ts
+++ b/x-pack/plugins/lists/server/services/lists/create_list.ts
@@ -72,7 +72,7 @@ export const createList = async ({
updated_by: user,
version,
};
- const { body: response } = await esClient.index({
+ const response = await esClient.index({
body,
id,
index: listIndex,
diff --git a/x-pack/plugins/lists/server/services/lists/find_list.ts b/x-pack/plugins/lists/server/services/lists/find_list.ts
index ed46c053cda9e..63f636370a144 100644
--- a/x-pack/plugins/lists/server/services/lists/find_list.ts
+++ b/x-pack/plugins/lists/server/services/lists/find_list.ts
@@ -63,7 +63,7 @@ export const findList = async ({
sortOrder,
});
- const { body: totalCount } = await esClient.count({
+ const totalCount = await esClient.count({
body: {
query,
},
@@ -75,7 +75,7 @@ export const findList = async ({
// Note: This typing of response = await esClient>
// is because when you pass in seq_no_primary_term: true it does a "fall through" type and you have
// to explicitly define the type .
- const { body: response } = await esClient.search({
+ const response = await esClient.search({
body: {
query,
search_after: scroll.searchAfter,
diff --git a/x-pack/plugins/lists/server/services/lists/get_list.test.ts b/x-pack/plugins/lists/server/services/lists/get_list.test.ts
index f599e5ef8b6c5..f9e64fe70eeca 100644
--- a/x-pack/plugins/lists/server/services/lists/get_list.test.ts
+++ b/x-pack/plugins/lists/server/services/lists/get_list.test.ts
@@ -26,9 +26,7 @@ describe('get_list', () => {
test('it returns a list as expected if the list is found', async () => {
const data = getSearchListMock();
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(data)
- );
+ esClient.search.mockResponse(data);
const list = await getList({ esClient, id: LIST_ID, listIndex: LIST_INDEX });
const expected = getListResponseMock();
expect(list).toEqual(expected);
@@ -38,9 +36,7 @@ describe('get_list', () => {
const data = getSearchListMock();
data.hits.hits = [];
const esClient = elasticsearchClientMock.createScopedClusterClient().asCurrentUser;
- esClient.search.mockReturnValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(data)
- );
+ esClient.search.mockResponse(data);
const list = await getList({ esClient, id: LIST_ID, listIndex: LIST_INDEX });
expect(list).toEqual(null);
});
diff --git a/x-pack/plugins/lists/server/services/lists/get_list.ts b/x-pack/plugins/lists/server/services/lists/get_list.ts
index 9b120ca0dd358..a1e34bdce6319 100644
--- a/x-pack/plugins/lists/server/services/lists/get_list.ts
+++ b/x-pack/plugins/lists/server/services/lists/get_list.ts
@@ -25,7 +25,7 @@ export const getList = async ({
// Note: This typing of response = await esClient