Skip to content

Commit

Permalink
Migrate SO management libs to typescript (#60555)
Browse files Browse the repository at this point in the history
* migrate most libs

* migrate last lib files

* fix get_relationships

* fix getSavedObject

* migrate tests to TS

* address review comments

* move test files outside of __jest__ folder
  • Loading branch information
pgayvallet authored Mar 26, 2020
1 parent f56d5c8 commit cec9165
Show file tree
Hide file tree
Showing 28 changed files with 413 additions and 358 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* under the License.
*/

import { extractExportDetails, SavedObjectsExportResultDetails } from '../extract_export_details';
import { extractExportDetails, SavedObjectsExportResultDetails } from './extract_export_details';

describe('extractExportDetails', () => {
const objLine = (id: string, type: string) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@

import { kfetch } from 'ui/kfetch';

export async function fetchExportByTypeAndSearch(types, search, includeReferencesDeep = false) {
export async function fetchExportByTypeAndSearch(
types: string[],
search: string | undefined,
includeReferencesDeep: boolean = false
): Promise<Blob> {
return await kfetch({
method: 'POST',
pathname: '/api/saved_objects/_export',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@

import { kfetch } from 'ui/kfetch';

export async function fetchExportObjects(objects, includeReferencesDeep = false) {
export async function fetchExportObjects(
objects: any[],
includeReferencesDeep: boolean = false
): Promise<Blob> {
return await kfetch({
method: 'POST',
pathname: '/api/saved_objects/_export',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@
*/

import { kfetch } from 'ui/kfetch';
import { SavedObjectsFindOptions } from 'src/core/public';
import { keysToCamelCaseShallow } from './case_conversion';

export async function findObjects(findOptions) {
export async function findObjects(findOptions: SavedObjectsFindOptions) {
const response = await kfetch({
method: 'GET',
pathname: '/api/kibana/management/saved_objects/_find',
query: findOptions,
query: findOptions as Record<string, any>,
});

return keysToCamelCaseShallow(response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@
* under the License.
*/

export function getDefaultTitle(object) {
export function getDefaultTitle(object: { id: string; type: string }) {
return `${object.type} [id=${object.id}]`;
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,24 @@
* under the License.
*/

import { getRelationships } from '../get_relationships';
import { getRelationships } from './get_relationships';

describe('getRelationships', () => {
it('should make an http request', async () => {
const $http = jest.fn();
const $http = jest.fn() as any;
const basePath = 'test';

await getRelationships('dashboard', 1, ['search', 'index-pattern'], $http, basePath);
await getRelationships('dashboard', '1', ['search', 'index-pattern'], $http, basePath);
expect($http.mock.calls.length).toBe(1);
});

it('should handle successful responses', async () => {
const $http = jest.fn().mockImplementation(() => ({ data: [1, 2] }));
const $http = jest.fn().mockImplementation(() => ({ data: [1, 2] })) as any;
const basePath = 'test';

const response = await getRelationships(
'dashboard',
1,
'1',
['search', 'index-pattern'],
$http,
basePath
Expand All @@ -44,23 +44,17 @@ describe('getRelationships', () => {

it('should handle errors', async () => {
const $http = jest.fn().mockImplementation(() => {
throw {
data: {
error: 'Test error',
statusCode: 500,
},
const err = new Error();
(err as any).data = {
error: 'Test error',
statusCode: 500,
};
});
throw err;
}) as any;
const basePath = 'test';

try {
await getRelationships('dashboard', 1, ['search', 'index-pattern'], $http, basePath);
} catch (e) {
// There isn't a great way to handle throwing exceptions
// with async/await but this seems to work :shrug:
expect(() => {
throw e;
}).toThrow();
}
await expect(
getRelationships('dashboard', '1', ['search', 'index-pattern'], $http, basePath)
).rejects.toThrowErrorMatchingInlineSnapshot(`"Test error"`);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,29 +17,37 @@
* under the License.
*/

import { IHttpService } from 'angular';
import { get } from 'lodash';
import { SavedObjectRelation } from '../types';

export async function getRelationships(type, id, savedObjectTypes, $http, basePath) {
export async function getRelationships(
type: string,
id: string,
savedObjectTypes: string[],
$http: IHttpService,
basePath: string
): Promise<SavedObjectRelation[]> {
const url = `${basePath}/api/kibana/management/saved_objects/relationships/${encodeURIComponent(
type
)}/${encodeURIComponent(id)}`;
const options = {
method: 'GET',
url,
params: {
savedObjectTypes: savedObjectTypes,
savedObjectTypes,
},
};

try {
const response = await $http(options);
return response ? response.data : undefined;
const response = await $http<SavedObjectRelation[]>(options);
return response?.data;
} catch (resp) {
const respBody = get(resp, 'data', {});
const respBody = get(resp, 'data', {}) as any;
const err = new Error(respBody.message || respBody.error || `${resp.status} Response`);

err.statusCode = respBody.statusCode || resp.status;
err.body = respBody;
(err as any).statusCode = respBody.statusCode || resp.status;
(err as any).body = respBody;

throw err;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,18 @@
* under the License.
*/

import { IHttpService } from 'angular';
import chrome from 'ui/chrome';

const apiBase = chrome.addBasePath('/api/kibana/management/saved_objects/scroll');
export async function getSavedObjectCounts($http, typesToInclude, searchString) {
const results = await $http.post(`${apiBase}/counts`, { typesToInclude, searchString });
export async function getSavedObjectCounts(
$http: IHttpService,
typesToInclude: string[],
searchString: string
): Promise<Record<string, number>> {
const results = await $http.post<Record<string, number>>(`${apiBase}/counts`, {
typesToInclude,
searchString,
});
return results.data;
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* under the License.
*/

export function getSavedObjectLabel(type) {
export function getSavedObjectLabel(type: string) {
switch (type) {
case 'index-pattern':
case 'index-patterns':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

import { kfetch } from 'ui/kfetch';

export async function importFile(file, overwriteAll = false) {
export async function importFile(file: Blob, overwriteAll: boolean = false) {
const formData = new FormData();
formData.append('file', file);
return await kfetch({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* 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.
*/

import { importLegacyFile } from './import_legacy_file';

describe('importFile', () => {
it('should import a file with valid json format', async () => {
const file = new File([`{"text": "foo"}`], 'file.json');

const imported = await importLegacyFile(file);
expect(imported).toEqual({ text: 'foo' });
});

it('should throw errors when file content is not parseable', async () => {
const file = new File([`not_parseable`], 'file.json');

await expect(importLegacyFile(file)).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unexpected token o in JSON at position 1"`
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
* under the License.
*/

export async function importLegacyFile(file, FileReader = window.FileReader) {
export async function importLegacyFile(file: File) {
return new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onload = ({ target: { result } }) => {
fr.onload = event => {
const result = event.target!.result as string;
try {
resolve(JSON.parse(result));
} catch (e) {
Expand Down
Loading

0 comments on commit cec9165

Please sign in to comment.