From 29beb44bf5ff5917bdbcb7dcca2f3aa3d9e43a53 Mon Sep 17 00:00:00 2001 From: Tomas Della Vedova Date: Wed, 10 Apr 2019 11:40:25 +0200 Subject: [PATCH] Improve typings (#813) The ApiResponse now accepts a generics that defaults to any, same for every API method that might need a body. --- ...ta_frame.get_data_frame_transform_stats.js | 125 ++++++ api/requestParams.d.ts | 407 ++++++++++-------- docs/reference.asciidoc | 118 +++++ docs/typescript.asciidoc | 180 ++++++-- lib/Transport.d.ts | 4 +- scripts/utils/generateRequestTypes.js | 4 +- test/types/index.ts | 35 ++ 7 files changed, 644 insertions(+), 229 deletions(-) create mode 100644 api/api/data_frame.get_data_frame_transform_stats.js diff --git a/api/api/data_frame.get_data_frame_transform_stats.js b/api/api/data_frame.get_data_frame_transform_stats.js new file mode 100644 index 000000000..730085eeb --- /dev/null +++ b/api/api/data_frame.get_data_frame_transform_stats.js @@ -0,0 +1,125 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +'use strict' + +/* eslint camelcase: 0 */ +/* eslint no-unused-vars: 0 */ + +function buildDataFrameGetDataFrameTransformStats (opts) { + // eslint-disable-next-line no-unused-vars + const { makeRequest, ConfigurationError, handleError } = opts + /** + * Perform a [data_frame.get_data_frame_transform_stats](https://www.elastic.co/guide/en/elasticsearch/reference/current/get-data-frame-transform-stats.html) request + * + * @param {string} transform_id - The id of the transform for which to get stats. '_all' or '*' implies all transforms + * @param {number} from - skips a number of transform stats, defaults to 0 + * @param {number} size - specifies a max number of transform stats to get, defaults to 100 + */ + + const acceptedQuerystring = [ + 'from', + 'size' + ] + + const snakeCase = { + + } + + return function dataFrameGetDataFrameTransformStats (params, options, callback) { + options = options || {} + if (typeof options === 'function') { + callback = options + options = {} + } + if (typeof params === 'function' || params == null) { + callback = params + params = {} + options = {} + } + + // check required parameters + if (params.body != null) { + const err = new ConfigurationError('This API does not require a body') + return handleError(err, callback) + } + + // validate headers object + if (options.headers != null && typeof options.headers !== 'object') { + const err = new ConfigurationError(`Headers should be an object, instead got: ${typeof options.headers}`) + return handleError(err, callback) + } + + var warnings = null + var { method, body, transformId, transform_id } = params + var querystring = semicopy(params, ['method', 'body', 'transformId', 'transform_id']) + + if (method == null) { + method = 'GET' + } + + var ignore = options.ignore || null + if (typeof ignore === 'number') { + ignore = [ignore] + } + + var path = '' + + path = '/' + '_data_frame' + '/' + 'transforms' + '/' + encodeURIComponent(transform_id || transformId) + '/' + '_stats' + + // build request object + const request = { + method, + path, + body: null, + querystring + } + + const requestOptions = { + ignore, + requestTimeout: options.requestTimeout || null, + maxRetries: options.maxRetries || null, + asStream: options.asStream || false, + headers: options.headers || null, + querystring: options.querystring || null, + compression: options.compression || false, + warnings + } + + return makeRequest(request, requestOptions, callback) + + function semicopy (obj, exclude) { + var target = {} + var keys = Object.keys(obj) + for (var i = 0, len = keys.length; i < len; i++) { + var key = keys[i] + if (exclude.indexOf(key) === -1) { + target[snakeCase[key] || key] = obj[key] + if (acceptedQuerystring.indexOf(snakeCase[key] || key) === -1) { + warnings = warnings || [] + warnings.push('Client - Unknown parameter: "' + key + '", sending it as query parameter') + } + } + } + return target + } + } +} + +module.exports = buildDataFrameGetDataFrameTransformStats diff --git a/api/requestParams.d.ts b/api/requestParams.d.ts index d5969d269..3df460251 100644 --- a/api/requestParams.d.ts +++ b/api/requestParams.d.ts @@ -27,7 +27,7 @@ export interface Generic { source?: string; } -export interface Bulk extends Generic { +export interface Bulk extends Generic { index?: string; type?: string; wait_for_active_shards?: string; @@ -38,7 +38,7 @@ export interface Bulk extends Generic { _source_excludes?: string | string[]; _source_includes?: string | string[]; pipeline?: string; - body: any; + body: T; } export interface CatAliases extends Generic { @@ -257,15 +257,15 @@ export interface CatThreadPool extends Generic { v?: boolean; } -export interface ClearScroll extends Generic { +export interface ClearScroll extends Generic { scroll_id?: string | string[]; - body?: any; + body?: T; } -export interface ClusterAllocationExplain extends Generic { +export interface ClusterAllocationExplain extends Generic { include_yes_decisions?: boolean; include_disk_info?: boolean; - body?: any; + body?: T; } export interface ClusterGetSettings extends Generic { @@ -294,24 +294,24 @@ export interface ClusterPendingTasks extends Generic { master_timeout?: string; } -export interface ClusterPutSettings extends Generic { +export interface ClusterPutSettings extends Generic { flat_settings?: boolean; master_timeout?: string; timeout?: string; - body: any; + body: T; } export interface ClusterRemoteInfo extends Generic { } -export interface ClusterReroute extends Generic { +export interface ClusterReroute extends Generic { dry_run?: boolean; explain?: boolean; retry_failed?: boolean; metric?: string | string[]; master_timeout?: string; timeout?: string; - body?: any; + body?: T; } export interface ClusterState extends Generic { @@ -333,7 +333,7 @@ export interface ClusterStats extends Generic { timeout?: string; } -export interface Count extends Generic { +export interface Count extends Generic { index?: string | string[]; type?: string | string[]; ignore_unavailable?: boolean; @@ -350,10 +350,10 @@ export interface Count extends Generic { df?: string; lenient?: boolean; terminate_after?: number; - body?: any; + body?: T; } -export interface Create extends Generic { +export interface Create extends Generic { id: string; index: string; type?: string; @@ -365,7 +365,7 @@ export interface Create extends Generic { version?: number; version_type?: 'internal' | 'external' | 'external_gte' | 'force'; pipeline?: string; - body: any; + body: T; } export interface Delete extends Generic { @@ -383,7 +383,7 @@ export interface Delete extends Generic { version_type?: 'internal' | 'external' | 'external_gte' | 'force'; } -export interface DeleteByQuery extends Generic { +export interface DeleteByQuery extends Generic { index: string | string[]; type?: string | string[]; analyzer?: string; @@ -418,7 +418,7 @@ export interface DeleteByQuery extends Generic { wait_for_completion?: boolean; requests_per_second?: number; slices?: number; - body: any; + body: T; } export interface DeleteByQueryRethrottle extends Generic { @@ -465,7 +465,7 @@ export interface ExistsSource extends Generic { version_type?: 'internal' | 'external' | 'external_gte' | 'force'; } -export interface Explain extends Generic { +export interface Explain extends Generic { id: string; index: string; type?: string; @@ -482,7 +482,7 @@ export interface Explain extends Generic { _source?: string | string[]; _source_excludes?: string | string[]; _source_includes?: string | string[]; - body?: any; + body?: T; } export interface FieldCaps extends Generic { @@ -533,7 +533,7 @@ export interface GetSource extends Generic { version_type?: 'internal' | 'external' | 'external_gte' | 'force'; } -export interface Index extends Generic { +export interface Index extends Generic { id?: string; index: string; type?: string; @@ -548,12 +548,12 @@ export interface Index extends Generic { if_seq_no?: number; if_primary_term?: number; pipeline?: string; - body: any; + body: T; } -export interface IndicesAnalyze extends Generic { +export interface IndicesAnalyze extends Generic { index?: string; - body?: any; + body?: T; } export interface IndicesClearCache extends Generic { @@ -576,13 +576,13 @@ export interface IndicesClose extends Generic { expand_wildcards?: 'open' | 'closed' | 'none' | 'all'; } -export interface IndicesCreate extends Generic { +export interface IndicesCreate extends Generic { index: string; include_type_name?: boolean; wait_for_active_shards?: string; timeout?: string; master_timeout?: string; - body?: any; + body?: T; } export interface IndicesDelete extends Generic { @@ -749,15 +749,15 @@ export interface IndicesOpen extends Generic { wait_for_active_shards?: string; } -export interface IndicesPutAlias extends Generic { +export interface IndicesPutAlias extends Generic { index: string | string[]; name: string; timeout?: string; master_timeout?: string; - body?: any; + body?: T; } -export interface IndicesPutMapping extends Generic { +export interface IndicesPutMapping extends Generic { index?: string | string[]; type?: string; include_type_name?: boolean; @@ -766,10 +766,10 @@ export interface IndicesPutMapping extends Generic { ignore_unavailable?: boolean; allow_no_indices?: boolean; expand_wildcards?: 'open' | 'closed' | 'none' | 'all'; - body: any; + body: T; } -export interface IndicesPutSettings extends Generic { +export interface IndicesPutSettings extends Generic { index?: string | string[]; master_timeout?: string; timeout?: string; @@ -778,10 +778,10 @@ export interface IndicesPutSettings extends Generic { allow_no_indices?: boolean; expand_wildcards?: 'open' | 'closed' | 'none' | 'all'; flat_settings?: boolean; - body: any; + body: T; } -export interface IndicesPutTemplate extends Generic { +export interface IndicesPutTemplate extends Generic { name: string; include_type_name?: boolean; order?: number; @@ -789,7 +789,7 @@ export interface IndicesPutTemplate extends Generic { timeout?: string; master_timeout?: string; flat_settings?: boolean; - body: any; + body: T; } export interface IndicesRecovery extends Generic { @@ -805,7 +805,7 @@ export interface IndicesRefresh extends Generic { expand_wildcards?: 'open' | 'closed' | 'none' | 'all'; } -export interface IndicesRollover extends Generic { +export interface IndicesRollover extends Generic { alias: string; new_index?: string; include_type_name?: boolean; @@ -813,7 +813,7 @@ export interface IndicesRollover extends Generic { dry_run?: boolean; master_timeout?: string; wait_for_active_shards?: string; - body?: any; + body?: T; } export interface IndicesSegments extends Generic { @@ -832,24 +832,24 @@ export interface IndicesShardStores extends Generic { expand_wildcards?: 'open' | 'closed' | 'none' | 'all'; } -export interface IndicesShrink extends Generic { +export interface IndicesShrink extends Generic { index: string; target: string; copy_settings?: boolean; timeout?: string; master_timeout?: string; wait_for_active_shards?: string; - body?: any; + body?: T; } -export interface IndicesSplit extends Generic { +export interface IndicesSplit extends Generic { index: string; target: string; copy_settings?: boolean; timeout?: string; master_timeout?: string; wait_for_active_shards?: string; - body?: any; + body?: T; } export interface IndicesStats extends Generic { @@ -864,10 +864,10 @@ export interface IndicesStats extends Generic { include_segment_file_sizes?: boolean; } -export interface IndicesUpdateAliases extends Generic { +export interface IndicesUpdateAliases extends Generic { timeout?: string; master_timeout?: string; - body: any; + body: T; } export interface IndicesUpgrade extends Generic { @@ -879,7 +879,7 @@ export interface IndicesUpgrade extends Generic { only_ancient_segments?: boolean; } -export interface IndicesValidateQuery extends Generic { +export interface IndicesValidateQuery extends Generic { index?: string | string[]; type?: string | string[]; explain?: boolean; @@ -894,7 +894,7 @@ export interface IndicesValidateQuery extends Generic { lenient?: boolean; rewrite?: boolean; all_shards?: boolean; - body?: any; + body?: T; } export interface Info extends Generic { @@ -914,20 +914,20 @@ export interface IngestGetPipeline extends Generic { export interface IngestProcessorGrok extends Generic { } -export interface IngestPutPipeline extends Generic { +export interface IngestPutPipeline extends Generic { id: string; master_timeout?: string; timeout?: string; - body: any; + body: T; } -export interface IngestSimulate extends Generic { +export interface IngestSimulate extends Generic { id?: string; verbose?: boolean; - body: any; + body: T; } -export interface Mget extends Generic { +export interface Mget extends Generic { index?: string; type?: string; stored_fields?: string | string[]; @@ -938,10 +938,10 @@ export interface Mget extends Generic { _source?: string | string[]; _source_excludes?: string | string[]; _source_includes?: string | string[]; - body: any; + body: T; } -export interface Msearch extends Generic { +export interface Msearch extends Generic { index?: string | string[]; type?: string | string[]; search_type?: 'query_then_fetch' | 'query_and_fetch' | 'dfs_query_then_fetch' | 'dfs_query_and_fetch'; @@ -951,10 +951,10 @@ export interface Msearch extends Generic { max_concurrent_shard_requests?: number; rest_total_hits_as_int?: boolean; ccs_minimize_roundtrips?: boolean; - body: any; + body: T; } -export interface MsearchTemplate extends Generic { +export interface MsearchTemplate extends Generic { index?: string | string[]; type?: string | string[]; search_type?: 'query_then_fetch' | 'query_and_fetch' | 'dfs_query_then_fetch' | 'dfs_query_and_fetch'; @@ -962,10 +962,10 @@ export interface MsearchTemplate extends Generic { max_concurrent_searches?: number; rest_total_hits_as_int?: boolean; ccs_minimize_roundtrips?: boolean; - body: any; + body: T; } -export interface Mtermvectors extends Generic { +export interface Mtermvectors extends Generic { index?: string; type?: string; ids?: string | string[]; @@ -981,7 +981,7 @@ export interface Mtermvectors extends Generic { realtime?: boolean; version?: number; version_type?: 'internal' | 'external' | 'external_gte' | 'force'; - body?: any; + body?: T; } export interface NodesHotThreads extends Generic { @@ -1029,23 +1029,23 @@ export interface NodesUsage extends Generic { export interface Ping extends Generic { } -export interface PutScript extends Generic { +export interface PutScript extends Generic { id: string; context?: string; timeout?: string; master_timeout?: string; - body: any; + body: T; } -export interface RankEval extends Generic { +export interface RankEval extends Generic { index?: string | string[]; ignore_unavailable?: boolean; allow_no_indices?: boolean; expand_wildcards?: 'open' | 'closed' | 'none' | 'all'; - body: any; + body: T; } -export interface Reindex extends Generic { +export interface Reindex extends Generic { refresh?: boolean; timeout?: string; wait_for_active_shards?: string; @@ -1053,7 +1053,7 @@ export interface Reindex extends Generic { requests_per_second?: number; scroll?: string; slices?: number; - body: any; + body: T; } export interface ReindexRethrottle extends Generic { @@ -1061,23 +1061,32 @@ export interface ReindexRethrottle extends Generic { requests_per_second: number; } -export interface RenderSearchTemplate extends Generic { +export interface RenderSearchTemplate extends Generic { id?: string; - body?: any; + body?: T; } +<<<<<<< HEAD export interface ScriptsPainlessExecute extends Generic { body?: any; +======= +export interface ScriptsPainlessContext extends Generic { + context?: string; } -export interface Scroll extends Generic { +export interface ScriptsPainlessExecute extends Generic { + body?: T; +>>>>>>> a21281f... Improve typings (#813) +} + +export interface Scroll extends Generic { scroll_id?: string; scroll?: string; rest_total_hits_as_int?: boolean; - body?: any; + body?: T; } -export interface Search extends Generic { +export interface Search extends Generic { index?: string | string[]; type?: string | string[]; analyzer?: string; @@ -1122,7 +1131,7 @@ export interface Search extends Generic { max_concurrent_shard_requests?: number; pre_filter_shard_size?: number; rest_total_hits_as_int?: boolean; - body?: any; + body?: T; } export interface SearchShards extends Generic { @@ -1135,7 +1144,7 @@ export interface SearchShards extends Generic { expand_wildcards?: 'open' | 'closed' | 'none' | 'all'; } -export interface SearchTemplate extends Generic { +export interface SearchTemplate extends Generic { index?: string | string[]; type?: string | string[]; ignore_unavailable?: boolean; @@ -1151,23 +1160,23 @@ export interface SearchTemplate extends Generic { typed_keys?: boolean; rest_total_hits_as_int?: boolean; ccs_minimize_roundtrips?: boolean; - body: any; + body: T; } -export interface SnapshotCreate extends Generic { +export interface SnapshotCreate extends Generic { repository: string; snapshot: string; master_timeout?: string; wait_for_completion?: boolean; - body?: any; + body?: T; } -export interface SnapshotCreateRepository extends Generic { +export interface SnapshotCreateRepository extends Generic { repository: string; master_timeout?: string; timeout?: string; verify?: boolean; - body: any; + body: T; } export interface SnapshotDelete extends Generic { @@ -1196,12 +1205,12 @@ export interface SnapshotGetRepository extends Generic { local?: boolean; } -export interface SnapshotRestore extends Generic { +export interface SnapshotRestore extends Generic { repository: string; snapshot: string; master_timeout?: string; wait_for_completion?: boolean; - body?: any; + body?: T; } export interface SnapshotStatus extends Generic { @@ -1240,7 +1249,7 @@ export interface TasksList extends Generic { timeout?: string; } -export interface Termvectors extends Generic { +export interface Termvectors extends Generic { index: string; type?: string; id?: string; @@ -1256,10 +1265,10 @@ export interface Termvectors extends Generic { realtime?: boolean; version?: number; version_type?: 'internal' | 'external' | 'external_gte' | 'force'; - body?: any; + body?: T; } -export interface Update extends Generic { +export interface Update extends Generic { id: string; index: string; type?: string; @@ -1275,10 +1284,10 @@ export interface Update extends Generic { timeout?: string; if_seq_no?: number; if_primary_term?: number; - body: any; + body: T; } -export interface UpdateByQuery extends Generic { +export interface UpdateByQuery extends Generic { index: string | string[]; type?: string | string[]; analyzer?: string; @@ -1315,7 +1324,7 @@ export interface UpdateByQuery extends Generic { wait_for_completion?: boolean; requests_per_second?: number; slices?: number; - body?: any; + body?: T; } export interface UpdateByQueryRethrottle extends Generic { @@ -1327,10 +1336,10 @@ export interface CcrDeleteAutoFollowPattern extends Generic { name: string; } -export interface CcrFollow extends Generic { +export interface CcrFollow extends Generic { index: string; wait_for_active_shards?: string; - body: any; + body: T; } export interface CcrFollowInfo extends Generic { @@ -1341,9 +1350,9 @@ export interface CcrFollowStats extends Generic { index: string | string[]; } -export interface CcrForgetFollower extends Generic { +export interface CcrForgetFollower extends Generic { index: string; - body: any; + body: T; } export interface CcrGetAutoFollowPattern extends Generic { @@ -1354,14 +1363,14 @@ export interface CcrPauseFollow extends Generic { index: string; } -export interface CcrPutAutoFollowPattern extends Generic { +export interface CcrPutAutoFollowPattern extends Generic { name: string; - body: any; + body: T; } -export interface CcrResumeFollow extends Generic { +export interface CcrResumeFollow extends Generic { index: string; - body?: any; + body?: T; } export interface CcrStats extends Generic { @@ -1371,12 +1380,52 @@ export interface CcrUnfollow extends Generic { index: string; } +<<<<<<< HEAD export interface GraphExplore extends Generic { +======= +export interface DataFrameDeleteDataFrameTransform extends Generic { + transform_id: string; +} + +export interface DataFrameGetDataFrameTransform extends Generic { + transform_id?: string; + from?: number; + size?: number; +} + +export interface DataFrameGetDataFrameTransformStats extends Generic { + transform_id?: string; + from?: number; + size?: number; +} + +export interface DataFramePreviewDataFrameTransform extends Generic { + body: T; +} + +export interface DataFramePutDataFrameTransform extends Generic { + transform_id: string; + body: T; +} + +export interface DataFrameStartDataFrameTransform extends Generic { + transform_id: string; + timeout?: string; +} + +export interface DataFrameStopDataFrameTransform extends Generic { + transform_id: string; + wait_for_completion?: boolean; + timeout?: string; +} + +export interface GraphExplore extends Generic { +>>>>>>> a21281f... Improve typings (#813) index?: string | string[]; type?: string | string[]; routing?: string; timeout?: string; - body?: any; + body?: T; } export interface IlmDeleteLifecycle extends Generic { @@ -1394,14 +1443,14 @@ export interface IlmGetLifecycle extends Generic { export interface IlmGetStatus extends Generic { } -export interface IlmMoveToStep extends Generic { +export interface IlmMoveToStep extends Generic { index?: string; - body?: any; + body?: T; } -export interface IlmPutLifecycle extends Generic { +export interface IlmPutLifecycle extends Generic { policy?: string; - body?: any; + body?: T; } export interface IlmRemovePolicy extends Generic { @@ -1451,9 +1500,9 @@ export interface LicenseGetBasicStatus extends Generic { export interface LicenseGetTrialStatus extends Generic { } -export interface LicensePost extends Generic { +export interface LicensePost extends Generic { acknowledge?: boolean; - body?: any; + body?: T; } export interface LicensePostStartBasic extends Generic { @@ -1469,12 +1518,12 @@ export interface MigrationDeprecations extends Generic { index?: string; } -export interface MlCloseJob extends Generic { +export interface MlCloseJob extends Generic { job_id: string; allow_no_jobs?: boolean; force?: boolean; timeout?: string; - body?: any; + body?: T; } export interface MlDeleteCalendar extends Generic { @@ -1521,7 +1570,7 @@ export interface MlDeleteModelSnapshot extends Generic { snapshot_id: string; } -export interface MlFindFileStructure extends Generic { +export interface MlFindFileStructure extends Generic { lines_to_sample?: number; timeout?: string; charset?: string; @@ -1535,17 +1584,17 @@ export interface MlFindFileStructure extends Generic { timestamp_field?: string; timestamp_format?: string; explain?: boolean; - body: any; + body: T; } -export interface MlFlushJob extends Generic { +export interface MlFlushJob extends Generic { job_id: string; calc_interim?: boolean; start?: string; end?: string; advance_time?: string; skip_time?: string; - body?: any; + body?: T; } export interface MlForecast extends Generic { @@ -1554,7 +1603,7 @@ export interface MlForecast extends Generic { expires_in?: string; } -export interface MlGetBuckets extends Generic { +export interface MlGetBuckets extends Generic { job_id: string; timestamp?: string; expand?: boolean; @@ -1566,7 +1615,7 @@ export interface MlGetBuckets extends Generic { anomaly_score?: number; sort?: string; desc?: boolean; - body?: any; + body?: T; } export interface MlGetCalendarEvents extends Generic { @@ -1578,19 +1627,19 @@ export interface MlGetCalendarEvents extends Generic { size?: number; } -export interface MlGetCalendars extends Generic { +export interface MlGetCalendars extends Generic { calendar_id?: string; from?: number; size?: number; - body?: any; + body?: T; } -export interface MlGetCategories extends Generic { +export interface MlGetCategories extends Generic { job_id: string; category_id?: number; from?: number; size?: number; - body?: any; + body?: T; } export interface MlGetDatafeedStats extends Generic { @@ -1609,7 +1658,7 @@ export interface MlGetFilters extends Generic { size?: number; } -export interface MlGetInfluencers extends Generic { +export interface MlGetInfluencers extends Generic { job_id: string; exclude_interim?: boolean; from?: number; @@ -1619,7 +1668,7 @@ export interface MlGetInfluencers extends Generic { influencer_score?: number; sort?: string; desc?: boolean; - body?: any; + body?: T; } export interface MlGetJobStats extends Generic { @@ -1632,7 +1681,7 @@ export interface MlGetJobs extends Generic { allow_no_jobs?: boolean; } -export interface MlGetModelSnapshots extends Generic { +export interface MlGetModelSnapshots extends Generic { job_id: string; snapshot_id?: string; from?: number; @@ -1641,10 +1690,10 @@ export interface MlGetModelSnapshots extends Generic { end?: string; sort?: string; desc?: boolean; - body?: any; + body?: T; } -export interface MlGetOverallBuckets extends Generic { +export interface MlGetOverallBuckets extends Generic { job_id: string; top_n?: number; bucket_span?: string; @@ -1653,10 +1702,10 @@ export interface MlGetOverallBuckets extends Generic { start?: string; end?: string; allow_no_jobs?: boolean; - body?: any; + body?: T; } -export interface MlGetRecords extends Generic { +export interface MlGetRecords extends Generic { job_id: string; exclude_interim?: boolean; from?: number; @@ -1666,7 +1715,7 @@ export interface MlGetRecords extends Generic { record_score?: number; sort?: string; desc?: boolean; - body?: any; + body?: T; } export interface MlInfo extends Generic { @@ -1678,25 +1727,25 @@ export interface MlOpenJob extends Generic { timeout?: string; } -export interface MlPostCalendarEvents extends Generic { +export interface MlPostCalendarEvents extends Generic { calendar_id: string; - body: any; + body: T; } -export interface MlPostData extends Generic { +export interface MlPostData extends Generic { job_id: string; reset_start?: string; reset_end?: string; - body: any; + body: T; } export interface MlPreviewDatafeed extends Generic { datafeed_id: string; } -export interface MlPutCalendar extends Generic { +export interface MlPutCalendar extends Generic { calendar_id: string; - body?: any; + body?: T; } export interface MlPutCalendarJob extends Generic { @@ -1704,26 +1753,26 @@ export interface MlPutCalendarJob extends Generic { job_id: string; } -export interface MlPutDatafeed extends Generic { +export interface MlPutDatafeed extends Generic { datafeed_id: string; - body: any; + body: T; } -export interface MlPutFilter extends Generic { +export interface MlPutFilter extends Generic { filter_id: string; - body: any; + body: T; } -export interface MlPutJob extends Generic { +export interface MlPutJob extends Generic { job_id: string; - body: any; + body: T; } -export interface MlRevertModelSnapshot extends Generic { +export interface MlRevertModelSnapshot extends Generic { job_id: string; snapshot_id: string; delete_intervening_results?: boolean; - body?: any; + body?: T; } export interface MlSetUpgradeMode extends Generic { @@ -1731,12 +1780,12 @@ export interface MlSetUpgradeMode extends Generic { timeout?: string; } -export interface MlStartDatafeed extends Generic { +export interface MlStartDatafeed extends Generic { datafeed_id: string; start?: string; end?: string; timeout?: string; - body?: any; + body?: T; } export interface MlStopDatafeed extends Generic { @@ -1746,41 +1795,41 @@ export interface MlStopDatafeed extends Generic { timeout?: string; } -export interface MlUpdateDatafeed extends Generic { +export interface MlUpdateDatafeed extends Generic { datafeed_id: string; - body: any; + body: T; } -export interface MlUpdateFilter extends Generic { +export interface MlUpdateFilter extends Generic { filter_id: string; - body: any; + body: T; } -export interface MlUpdateJob extends Generic { +export interface MlUpdateJob extends Generic { job_id: string; - body: any; + body: T; } -export interface MlUpdateModelSnapshot extends Generic { +export interface MlUpdateModelSnapshot extends Generic { job_id: string; snapshot_id: string; - body: any; + body: T; } -export interface MlValidate extends Generic { - body: any; +export interface MlValidate extends Generic { + body: T; } -export interface MlValidateDetector extends Generic { - body: any; +export interface MlValidateDetector extends Generic { + body: T; } -export interface MonitoringBulk extends Generic { +export interface MonitoringBulk extends Generic { type?: string; system_id?: string; system_api_version?: string; interval?: string; - body: any; + body: T; } export interface RollupDeleteJob extends Generic { @@ -1799,17 +1848,17 @@ export interface RollupGetRollupIndexCaps extends Generic { index: string; } -export interface RollupPutJob extends Generic { +export interface RollupPutJob extends Generic { id: string; - body: any; + body: T; } -export interface RollupRollupSearch extends Generic { +export interface RollupRollupSearch extends Generic { index: string | string[]; type?: string; typed_keys?: boolean; rest_total_hits_as_int?: boolean; - body: any; + body: T; } export interface RollupStartJob extends Generic { @@ -1825,10 +1874,10 @@ export interface RollupStopJob extends Generic { export interface SecurityAuthenticate extends Generic { } -export interface SecurityChangePassword extends Generic { +export interface SecurityChangePassword extends Generic { username?: string; refresh?: 'true' | 'false' | 'wait_for'; - body: any; + body: T; } export interface SecurityClearCachedRealms extends Generic { @@ -1840,9 +1889,9 @@ export interface SecurityClearCachedRoles extends Generic { name: string | string[]; } -export interface SecurityCreateApiKey extends Generic { +export interface SecurityCreateApiKey extends Generic { refresh?: 'true' | 'false' | 'wait_for'; - body: any; + body: T; } export interface SecurityDeletePrivileges extends Generic { @@ -1896,8 +1945,8 @@ export interface SecurityGetRoleMapping extends Generic { name?: string; } -export interface SecurityGetToken extends Generic { - body: any; +export interface SecurityGetToken extends Generic { + body: T; } export interface SecurityGetUser extends Generic { @@ -1907,53 +1956,53 @@ export interface SecurityGetUser extends Generic { export interface SecurityGetUserPrivileges extends Generic { } -export interface SecurityHasPrivileges extends Generic { +export interface SecurityHasPrivileges extends Generic { user?: string; - body: any; + body: T; } -export interface SecurityInvalidateApiKey extends Generic { - body: any; +export interface SecurityInvalidateApiKey extends Generic { + body: T; } -export interface SecurityInvalidateToken extends Generic { - body: any; +export interface SecurityInvalidateToken extends Generic { + body: T; } -export interface SecurityPutPrivileges extends Generic { +export interface SecurityPutPrivileges extends Generic { refresh?: 'true' | 'false' | 'wait_for'; - body: any; + body: T; } -export interface SecurityPutRole extends Generic { +export interface SecurityPutRole extends Generic { name: string; refresh?: 'true' | 'false' | 'wait_for'; - body: any; + body: T; } -export interface SecurityPutRoleMapping extends Generic { +export interface SecurityPutRoleMapping extends Generic { name: string; refresh?: 'true' | 'false' | 'wait_for'; - body: any; + body: T; } -export interface SecurityPutUser extends Generic { +export interface SecurityPutUser extends Generic { username: string; refresh?: 'true' | 'false' | 'wait_for'; - body: any; + body: T; } -export interface SqlClearCursor extends Generic { - body: any; +export interface SqlClearCursor extends Generic { + body: T; } -export interface SqlQuery extends Generic { +export interface SqlQuery extends Generic { format?: string; - body: any; + body: T; } -export interface SqlTranslate extends Generic { - body: any; +export interface SqlTranslate extends Generic { + body: T; } export interface SslCertificates extends Generic { @@ -1976,23 +2025,23 @@ export interface WatcherDeleteWatch extends Generic { id: string; } -export interface WatcherExecuteWatch extends Generic { +export interface WatcherExecuteWatch extends Generic { id?: string; debug?: boolean; - body?: any; + body?: T; } export interface WatcherGetWatch extends Generic { id: string; } -export interface WatcherPutWatch extends Generic { +export interface WatcherPutWatch extends Generic { id: string; active?: boolean; version?: number; if_seq_no?: number; if_primary_term?: number; - body?: any; + body?: T; } export interface WatcherStart extends Generic { diff --git a/docs/reference.asciidoc b/docs/reference.asciidoc index 3c6546d96..128222e51 100644 --- a/docs/reference.asciidoc +++ b/docs/reference.asciidoc @@ -4282,6 +4282,124 @@ link:http://www.elastic.co/guide/en/elasticsearch/reference/current[Reference] |=== +<<<<<<< HEAD +======= +=== dataFrame.deleteDataFrameTransform +[source,js] +---- +client.dataFrame.deleteDataFrameTransform([params] [, options] [, callback]) +---- +link:{ref}/delete-data-frame-transform.html[Reference] +[cols=2*] +|=== +|`transform_id` or `transformId` +|`string` - The id of the transform to delete + +|=== + +=== dataFrame.getDataFrameTransform +[source,js] +---- +client.dataFrame.getDataFrameTransform([params] [, options] [, callback]) +---- +link:{ref}/get-data-frame-transform.html[Reference] +[cols=2*] +|=== +|`transform_id` or `transformId` +|`string` - The id or comma delimited list of id expressions of the transforms to get, '_all' or '*' implies get all transforms + +|`from` +|`number` - skips a number of transform configs, defaults to 0 + +|`size` +|`number` - specifies a max number of transforms to get, defaults to 100 + +|=== + +=== dataFrame.getDataFrameTransformStats +[source,js] +---- +client.dataFrame.getDataFrameTransformStats([params] [, options] [, callback]) +---- +link:{ref}/get-data-frame-transform-stats.html[Reference] +[cols=2*] +|=== +|`transform_id` or `transformId` +|`string` - The id of the transform for which to get stats. '_all' or '*' implies all transforms + +|`from` +|`number` - skips a number of transform stats, defaults to 0 + +|`size` +|`number` - specifies a max number of transform stats to get, defaults to 100 + +|=== + +=== dataFrame.previewDataFrameTransform +[source,js] +---- +client.dataFrame.previewDataFrameTransform([params] [, options] [, callback]) +---- +link:{ref}/preview-data-frame-transform.html[Reference] +[cols=2*] +|=== +|`body` +|`object` - The definition for the data_frame transform to preview + +|=== + +=== dataFrame.putDataFrameTransform +[source,js] +---- +client.dataFrame.putDataFrameTransform([params] [, options] [, callback]) +---- +link:{ref}/put-data-frame-transform.html[Reference] +[cols=2*] +|=== +|`transform_id` or `transformId` +|`string` - The id of the new transform. + +|`body` +|`object` - The data frame transform definition + +|=== + +=== dataFrame.startDataFrameTransform +[source,js] +---- +client.dataFrame.startDataFrameTransform([params] [, options] [, callback]) +---- +link:{ref}/start-data-frame-transform.html[Reference] +[cols=2*] +|=== +|`transform_id` or `transformId` +|`string` - The id of the transform to start + +|`timeout` +|`string` - Controls the time to wait for the transform to start + +|=== + +=== dataFrame.stopDataFrameTransform +[source,js] +---- +client.dataFrame.stopDataFrameTransform([params] [, options] [, callback]) +---- +link:{ref}/stop-data-frame-transform.html[Reference] +[cols=2*] +|=== +|`transform_id` or `transformId` +|`string` - The id of the transform to stop + +|`wait_for_completion` or `waitForCompletion` +|`boolean` - Whether to wait for the transform to fully stop before returning or not. Default to false + +|`timeout` +|`string` - Controls the time to wait until the transform has stopped. Default to 30 seconds + +|=== + +>>>>>>> a21281f... Improve typings (#813) === graph.explore [source,js] ---- diff --git a/docs/typescript.asciidoc b/docs/typescript.asciidoc index 4dbe92054..237b27084 100644 --- a/docs/typescript.asciidoc +++ b/docs/typescript.asciidoc @@ -3,58 +3,146 @@ The client offers a first-class support for TypeScript, since it ships the type definitions for every exposed API. -While the client offers type definitions for Request parameters, Request bodies and responses are shipped with `any` because there is not an official spec that defines them, so we cannot make guarantees over them (but since they are shipped with `any`, you can easily override them with your own typing definitions). - NOTE: If you are using TypeScript you will be required to use _snake_case_ style to define the API parameters instead of _camelCase_. -=== How to extend the provided typings? -Extend the provided typings is very straightforward, you should declare a custom `.d.ts` file and then write inside your type extensions, following there is an example of how do it. +Other than the types for the surface API, the client offers the types for every request method, via the `RequestParams`, if you need the types for a search request for instance, you can access them via `RequestParams.Search`. +Every API that supports a body, accepts a https://www.typescriptlang.org/docs/handbook/generics.html[generics] which represents the type of the request body, if you don't configure anything, it will default to `any`. + +For example: + [source,ts] ---- -declare module '@elastic/elasticsearch' { - export interface ShardsResponse { - total: number; - successful: number; - failed: number; - skipped: number; - } +import { RequestParams } from '@elastic/elasticsearch' - export interface Explanation { - value: number; - description: string; - details: Explanation[]; - } - - export interface SearchResponse { - took: number; - timed_out: boolean; - _scroll_id?: string; - _shards: ShardsResponse; - hits: { - total: number; - max_score: number; - hits: Array<{ - _index: string; - _type: string; - _id: string; - _score: number; - _source: T; - _version?: number; - _explanation?: Explanation; - fields?: any; - highlight?: any; - inner_hits?: any; - matched_queries?: string[]; - sort?: string[]; - }>; - }; - aggregations?: any; - } - - export interface MSearchResponse { - responses?: Array>; +interface SearchBody { + query: { + match: { foo: string } } } -export {}; +const searchParams: RequestParams.Search = { + index: 'test', + body: { + query: { + match: { foo: 'bar' } + } + } +} + +// This is valid as well +const searchParams: RequestParams.Search = { + index: 'test', + body: { + query: { + match: { foo: 'bar' } + } + } +} +---- + +You can find the type definiton of a response in `ApiResponse`, which accepts a generics as well if you want to specify the body type, otherwise it defaults to `any`. + +[source,ts] +---- +interface SearchResponse { + hits: { + hits: Array<{ + _source: T; + }> + } +} + +// Define the intefrace of the source object +interface Source { + foo: string +} + +client.search(searchParams) + .then((response: ApiResponse>) => console.log(response)) + .catch((err: Error) => {}) +---- + +=== A complete example + +[source,ts] +---- +import { + Client, + // Object that contains the type definitions of every API method + RequestParams, + // Interface of the generic API response + ApiResponse, +} from '@elastic/elasticsearch' + +const client = new Client({ node: 'http://localhost:9200' }) + +// Define the type of the body for the Search request +interface SearchBody { + query: { + match: { foo: string } + } +} + +// Complete definition of the Search response +interface ShardsResponse { + total: number; + successful: number; + failed: number; + skipped: number; +} + +interface Explanation { + value: number; + description: string; + details: Explanation[]; +} + +interface SearchResponse { + took: number; + timed_out: boolean; + _scroll_id?: string; + _shards: ShardsResponse; + hits: { + total: number; + max_score: number; + hits: Array<{ + _index: string; + _type: string; + _id: string; + _score: number; + _source: T; + _version?: number; + _explanation?: Explanation; + fields?: any; + highlight?: any; + inner_hits?: any; + matched_queries?: string[]; + sort?: string[]; + }>; + }; + aggregations?: any; +} + +// Define the intefrace of the source object +interface Source { + foo: string +} + +async function run (): Promise { + // Define the search parameters + const searchParams: RequestParams.Search = { + index: 'test', + body: { + query: { + match: { foo: 'bar' } + } + } + } + + // Craft the final type definition + const response: ApiResponse> = await client.search(searchParams) + console.log(response.body) +} + +run().catch(console.log) ---- diff --git a/lib/Transport.d.ts b/lib/Transport.d.ts index 28033e292..3a349cbf1 100644 --- a/lib/Transport.d.ts +++ b/lib/Transport.d.ts @@ -49,7 +49,7 @@ interface TransportOptions { headers?: anyObject; } -export interface RequestEvent { +export interface RequestEvent { body: any; statusCode: number | null; headers: anyObject | null; @@ -71,7 +71,7 @@ export interface RequestEvent { // ApiResponse and RequestEvent are the same thing // we are doing this for have more clear names -export interface ApiResponse extends RequestEvent {} +export interface ApiResponse extends RequestEvent {} declare type anyObject = { [key: string]: any; diff --git a/scripts/utils/generateRequestTypes.js b/scripts/utils/generateRequestTypes.js index e457e7e0b..edba2fa68 100644 --- a/scripts/utils/generateRequestTypes.js +++ b/scripts/utils/generateRequestTypes.js @@ -74,10 +74,10 @@ export interface Generic { } const code = ` -export interface ${name[0].toUpperCase() + name.slice(1)} extends Generic { +export interface ${name[0].toUpperCase() + name.slice(1)}${body ? '' : ''} extends Generic { ${partsArr.map(genLine).join('\n ')} ${paramsArr.map(genLine).join('\n ')} - ${body ? `body${body.required ? '' : '?'}: any;` : ''} + ${body ? `body${body.required ? '' : '?'}: T;` : ''} } ` diff --git a/test/types/index.ts b/test/types/index.ts index 20705bad1..6079906e6 100644 --- a/test/types/index.ts +++ b/test/types/index.ts @@ -22,6 +22,7 @@ import { Client, ApiResponse, + RequestParams, RequestEvent, ResurrectEvent, events, @@ -94,6 +95,40 @@ client.index({ .then((result: ApiResponse) => {}) .catch((err: Error) => {}) +// --- Use generics --- +// Define the search parameters +interface SearchBody { + query: { + match: { foo: string } + } +} +const searchParams: RequestParams.Search = { + index: 'test', + body: { + query: { + match: { foo: 'bar' } + } + } +} + +// Dewfine the interface of the search response +interface SearchResponse { + hits: { + hits: Array<{ + _source: T; + }> + } +} + +// Define the intefrace of the source object +interface Source { + foo: string +} + +client.search(searchParams) + .then((response: ApiResponse>) => console.log(response)) + .catch((err: Error) => {}) + // extend client client.extend('namespace.method', (options: ClientExtendsCallbackOptions) => { return function (params: any) {