Skip to content

Commit

Permalink
optimzize the code
Browse files Browse the repository at this point in the history
Signed-off-by: yubonluo <[email protected]>
  • Loading branch information
yubonluo committed Dec 19, 2024
1 parent dffc1b4 commit 06cd3ee
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 65 deletions.
9 changes: 7 additions & 2 deletions src/core/public/workspace/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/

import { WorkspaceAttribute } from '../../types';
import { SavedObjectsImportResponse } from '../saved_objects';

export type WorkspaceObject = WorkspaceAttribute & { readonly?: boolean; owner?: boolean };

Expand Down Expand Up @@ -35,9 +36,13 @@ export interface IWorkspaceClient {
* @param {Array<{ id: string; type: string }>} objects
* @param {string} targetWorkspace
* @param {boolean} includeReferencesDeep
* @returns {Promise<IResponse<any>>} result for this operation
* @returns {Promise<SavedObjectsImportResponse>} result for this operation
*/
copy(objects: any[], targetWorkspace: string, includeReferencesDeep?: boolean): Promise<any>;
copy(
objects: Array<{ id: string; type: string }>,
targetWorkspace: string,
includeReferencesDeep?: boolean
): Promise<SavedObjectsImportResponse>;

/**
* Associates a list of objects with the given workspace ID.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ export interface DuplicateResultFlyoutProps {
savedObjects: DuplicateObject[],
includeReferencesDeep: boolean,
targetWorkspace: string,
targetWorkspaceName: string,
isSolveErrorsOperation: boolean
targetWorkspaceName: string
) => Promise<void>;
targetWorkspace: string;
useUpdatedUX: boolean;
Expand Down Expand Up @@ -355,7 +354,7 @@ export class DuplicateResultFlyout extends React.Component<DuplicateResultFlyout
isLoading: true,
});

await onCopy(savedObjects, false, targetWorkspace, workspaceName, true);
await onCopy(savedObjects, false, targetWorkspace, workspaceName);

this.setState({
isLoading: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1021,37 +1021,6 @@ describe('SavedObjectsTable', () => {
});
});

it('should catch error when duplicating selected object is failed', async () => {
const component = shallowRender({ applications, workspaces });
component.setState({ isShowingDuplicateModal: true });

const mockCopy = jest.fn().mockResolvedValue({ error: 'error' });
workspaces.client$.next({ copy: mockCopy });
const client = workspaces.client$.getValue();

// Ensure all promises resolve
await new Promise((resolve) => process.nextTick(resolve));
// Ensure the state changes are reflected
component.update();

await component.instance().onDuplicate(mockSelectedSavedObjects, false, 'workspace2', 'bar');

expect(client?.copy).toHaveBeenCalledWith(
[
{ id: '1', type: 'dashboard' },
{ id: '2', type: 'dashboard' },
],
'workspace2',
false
);
component.update();

expect(notifications.toasts.addDanger).toHaveBeenCalledWith({
title: 'Unable to copy 2 saved objects.',
text: 'error',
});
});

it('should show error toast when copy is fail', async () => {
const component = shallowRender({ applications, workspaces });
component.setState({ isShowingDuplicateModal: true });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -759,20 +759,18 @@ export class SavedObjectsTable extends Component<SavedObjectsTableProps, SavedOb
savedObjects: DuplicateObject[],
includeReferencesDeep: boolean,
targetWorkspace: string,
targetWorkspaceName: string,
isSolveErrorsOperation?: boolean
targetWorkspaceName: string
) => {
const { notifications, workspaces, useUpdatedUX } = this.props;
const workspaceClient = workspaces.client$.getValue();

const showErrorNotification = (text?: string) => {
const showErrorNotification = () => {
notifications.toasts.addDanger({
title: i18n.translate('savedObjectsManagement.objectsTable.duplicate.dangerNotification', {
defaultMessage:
'Unable to copy {useUpdatedUX, select, true {{errorCount, plural, one {# asset} other {# assets}}} other {{errorCount, plural, one {# saved object} other {# saved objects}}}}.',
values: { errorCount: savedObjects.length, useUpdatedUX },
}),
...(text && { text }),
});
};
if (!workspaceClient) {
Expand All @@ -786,25 +784,13 @@ export class SavedObjectsTable extends Component<SavedObjectsTableProps, SavedOb
targetWorkspace,
includeReferencesDeep
);
if (result?.error) {
showErrorNotification(result.error);
} else {
if (isSolveErrorsOperation) {
this.setState({
failedCopies: result?.errors || [],
successfulCopies: result?.successCount > 0 ? result.successResults : [],
targetWorkspaceName,
});
} else {
this.setState({
isShowingDuplicateResultFlyout: true,
failedCopies: result?.errors || [],
successfulCopies: result?.successCount > 0 ? result.successResults : [],
targetWorkspace,
targetWorkspaceName,
});
}
}
this.setState({
isShowingDuplicateResultFlyout: true,
failedCopies: result?.errors || [],
successfulCopies: result?.successResults || [],
targetWorkspace,
targetWorkspaceName,
});
} catch (e) {
showErrorNotification();
} finally {
Expand Down
6 changes: 3 additions & 3 deletions src/plugins/workspace/public/workspace_client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,14 @@ describe('#WorkspaceClient', () => {
const { workspaceClient, httpSetupMock } = getWorkspaceClient();
httpSetupMock.fetch.mockResolvedValue({
success: true,
result: {},
successCount: 1,
});
const body = JSON.stringify({
objects: [{ id: 1, type: 'url' }],
objects: [{ id: 'url_id', type: 'url' }],
targetWorkspace: 'workspace-1',
includeReferencesDeep: false,
});
await workspaceClient.copy([{ id: 1, type: 'url' }], 'workspace-1', false);
await workspaceClient.copy([{ id: 'url_id', type: 'url' }], 'workspace-1', false);
expect(httpSetupMock.fetch).toBeCalledWith('/api/workspaces/_duplicate_saved_objects', {
body,
method: 'POST',
Expand Down
8 changes: 5 additions & 3 deletions src/plugins/workspace/public/workspace_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
WorkspacesSetup,
IWorkspaceClient,
IWorkspaceResponse as IResponse,
SavedObjectsImportResponse,
} from '../../../core/public';
import { WorkspacePermissionMode } from '../common/constants';
import { SavedObjectPermissions, WorkspaceAttributeWithPermission } from '../../../core/types';
Expand Down Expand Up @@ -328,21 +329,22 @@ export class WorkspaceClient implements IWorkspaceClient {
* @param {Array<{ id: string; type: string }>} objects
* @param {string} targetWorkspace
* @param {boolean} includeReferencesDeep
* @returns {Promise<IResponse<any>>} result for this operation
* @returns {Promise<SavedObjectsImportResponse>} result for this operation
*/
public async copy(
objects: Array<{ id: string; type: string }>,
targetWorkspace: string,
includeReferencesDeep: boolean = true
): Promise<IResponse<any>> {
): Promise<SavedObjectsImportResponse> {
// throw 'err';
const path = this.getPath('_duplicate_saved_objects');
const body = {
objects,
targetWorkspace,
includeReferencesDeep,
};

const result = await this.safeFetch(path, {
const result = await this.http.fetch<SavedObjectsImportResponse>(path, {
method: 'POST',
body: JSON.stringify(body),
});
Expand Down

0 comments on commit 06cd3ee

Please sign in to comment.