Skip to content

Commit

Permalink
cleaning up http requests
Browse files Browse the repository at this point in the history
  • Loading branch information
jgowdyelastic committed Mar 11, 2020
1 parent 9d76469 commit 57d86a4
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 72 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,12 @@ function randomNumber(min, max) {
}

function saveWatch(watchModel) {
const path = '/api/watcher';
const url = `${path}/watch/${watchModel.id}`;
const path = `/api/watcher/watch/${watchModel.id}`;

return http({
url,
path,
method: 'PUT',
data: watchModel.upstreamJSON,
body: JSON.stringify(watchModel.upstreamJSON),
});
}

Expand Down Expand Up @@ -187,10 +186,9 @@ class CreateWatchService {

loadWatch(jobId) {
const id = `ml-${jobId}`;
const path = '/api/watcher';
const url = `${path}/watch/${id}`;
const path = `/api/watcher/watch/${id}`;
return http({
url,
path,
method: 'GET',
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { Observable } from 'rxjs';
import { HttpFetchOptionsWithPath } from 'kibana/public';
import { HttpFetchOptionsWithPath, HttpFetchOptions } from 'kibana/public';
import { getHttp } from '../util/dependency_cache';

function getResultHeaders(headers: HeadersInit): HeadersInit {
Expand All @@ -16,64 +16,40 @@ function getResultHeaders(headers: HeadersInit): HeadersInit {
} as HeadersInit;
}

// interface HttpOptions {
// url: string;
// method: string;
// headers?: any;
// data?: any;
// }

/**
* Function for making HTTP requests to Kibana's backend.
* Wrapper for Kibana's HttpHandler.
*/
export async function http(options: HttpFetchOptionsWithPath) {
if (!options?.path) {
function getFetchOptions(
options: HttpFetchOptionsWithPath
): { path: string; fetchOptions: HttpFetchOptions } {
if (!options.path) {
throw new Error('URL path is missing');
}

try {
let path = '';
path = path + (options.path || '');
const headers = getResultHeaders(options.headers ?? {});

const allHeaders = options.headers === undefined ? headers : { ...options.headers, ...headers };
const body = options.body === undefined ? null : JSON.stringify(options.body);

const payload: RequestInit = {
method: options.method || 'GET',
headers: allHeaders,
return {
path: options.path,
fetchOptions: {
credentials: 'same-origin',
};

if (body !== null) {
payload.body = body;
}

return await getHttp().fetch(path, payload);
} catch (e) {
throw new Error(e);
}
method: options.method || 'GET',
...(options.body ? { body: options.body } : {}),
...(options.query ? { query: options.query } : {}),
headers: getResultHeaders(options.headers ?? {}),
},
};
}

interface RequestOptions extends RequestInit {
body: BodyInit | any;
/**
* Function for making HTTP requests to Kibana's backend.
* Wrapper for Kibana's HttpHandler.
*/
export async function http<T>(options: HttpFetchOptionsWithPath): Promise<T> {
const { path, fetchOptions } = getFetchOptions(options);
return getHttp().fetch<T>(path, fetchOptions);
}

/**
* Function for making HTTP requests to Kibana's backend which returns an Observable
* with request cancellation support.
*/
export function http$<T>(path: string, options: RequestOptions): Observable<T> {
const requestInit: RequestInit = {
...options,
credentials: 'same-origin',
method: options.method || 'GET',
...(options.body ? { body: JSON.stringify(options.body) as string } : {}),
headers: getResultHeaders(options.headers ?? {}),
};

return fromHttpHandler<T>(path, requestInit);
export function http$<T>(options: HttpFetchOptionsWithPath): Observable<T> {
const { path, fetchOptions } = getFetchOptions(options);
return fromHttpHandler<T>(path, fetchOptions);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,19 @@ export const annotations = {
latestMs: number;
maxAnnotations: number;
}) {
return http$<{ annotations: Record<string, Annotation[]> }>(`${basePath()}/annotations`, {
const body = JSON.stringify(obj);
return http$<{ annotations: Record<string, Annotation[]> }>({
path: `${basePath()}/annotations`,
method: 'POST',
body: obj,
body,
});
},
indexAnnotation(obj: any) {
const body = JSON.stringify(obj);
return http({
path: `${basePath()}/annotations/index`,
method: 'PUT',
body: obj,
body,
});
},
deleteAnnotation(id: string) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,24 +47,27 @@ export const dataFrameAnalytics = {
});
},
createDataFrameAnalytics(analyticsId: string, analyticsConfig: any): Promise<any> {
const body = JSON.stringify(analyticsConfig);
return http({
path: `${basePath()}/data_frame/analytics/${analyticsId}`,
method: 'PUT',
body: analyticsConfig,
body,
});
},
evaluateDataFrameAnalytics(evaluateConfig: any): Promise<any> {
const body = JSON.stringify(evaluateConfig);
return http({
path: `${basePath()}/data_frame/_evaluate`,
method: 'POST',
body: evaluateConfig,
body,
});
},
explainDataFrameAnalytics(jobConfig: any): Promise<any> {
const body = JSON.stringify(jobConfig);
return http({
path: `${basePath()}/data_frame/analytics/_explain`,
method: 'POST',
body: jobConfig,
body,
});
},
deleteDataFrameAnalytics(analyticsId: string): Promise<any> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ import { basePath } from './index';

export const fileDatavisualizer = {
analyzeFile(file: string, params: Record<string, string> = {}) {
const body = JSON.stringify(file);
return http({
path: `${basePath()}/file_data_visualizer/analyze_file`,
method: 'POST',
body: file,
body,
query: params,
});
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export const ml = {
},

addJob({ jobId, job }: { jobId: string; job: Job }) {
const body = JSON.stringify({ job });
const body = JSON.stringify(job);
return http({
path: `${basePath()}/anomaly_detectors/${jobId}`,
method: 'PUT',
Expand Down Expand Up @@ -132,7 +132,7 @@ export const ml = {
},

updateJob({ jobId, job }: { jobId: string; job: Job }) {
const body = JSON.stringify({ job });
const body = JSON.stringify(job);
return http({
path: `${basePath()}/anomaly_detectors/${jobId}/_update`,
method: 'POST',
Expand All @@ -159,8 +159,9 @@ export const ml = {
},

validateCardinality$(job: CombinedJob): Observable<CardinalityValidationResults> {
const body = JSON.stringify({ job });
return http$(`${basePath()}/validate/cardinality`, {
const body = JSON.stringify(job);
return http$({
path: `${basePath()}/validate/cardinality`,
method: 'POST',
body,
});
Expand All @@ -181,7 +182,7 @@ export const ml = {
},

addDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: Datafeed }) {
const body = JSON.stringify({ datafeedConfig });
const body = JSON.stringify(datafeedConfig);
return http({
path: `${basePath()}/datafeeds/${datafeedId}`,
method: 'PUT',
Expand All @@ -190,7 +191,7 @@ export const ml = {
},

updateDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: Datafeed }) {
const body = JSON.stringify({ datafeedConfig });
const body = JSON.stringify(datafeedConfig);
return http({
path: `${basePath()}/datafeeds/${datafeedId}/_update`,
method: 'POST',
Expand Down Expand Up @@ -240,7 +241,7 @@ export const ml = {
},

validateDetector({ detector }: { detector: Detector }) {
const body = JSON.stringify({ detector });
const body = JSON.stringify(detector);
return http({
path: `${basePath()}/anomaly_detectors/_validate/detector`,
method: 'POST',
Expand Down Expand Up @@ -618,7 +619,8 @@ export const ml = {

esSearch$(obj: any): Observable<any> {
const body = JSON.stringify(obj);
return http$(`${basePath()}/es_search`, {
return http$({
path: `${basePath()}/es_search`,
method: 'POST',
body,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ export const results = {
influencersFilterQuery,
});

return http$(`${basePath()}/results/anomalies_table_data`, {
return http$({
path: `${basePath()}/results/anomalies_table_data`,
method: 'POST',
body,
});
Expand Down Expand Up @@ -91,7 +92,8 @@ export const results = {
latestMs: number
): Observable<PartitionFieldsDefinition> {
const body = JSON.stringify({ jobId, searchTerm, criteriaFields, earliestMs, latestMs });
return http$(`${basePath()}/results/partition_fields_values`, {
return http$({
path: `${basePath()}/results/partition_fields_values`,
method: 'POST',
body,
});
Expand Down

0 comments on commit 57d86a4

Please sign in to comment.