Improved error handling in collection and favorites actions
[arvados-workbench2.git] / src / store / collections / collection-create-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Dispatch } from "redux";
6 import { reset, startSubmit, stopSubmit, initialize } from 'redux-form';
7 import { RootState } from '~/store/store';
8 import { dialogActions } from "~/store/dialog/dialog-actions";
9 import { ServiceRepository } from '~/services/services';
10 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/services/common-service/common-resource-service";
11 import { uploadCollectionFiles } from './collection-upload-actions';
12 import { fileUploaderActions } from '~/store/file-uploader/file-uploader-actions';
13 import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions";
14
15 export interface CollectionCreateFormDialogData {
16     ownerUuid: string;
17     name: string;
18     description: string;
19 }
20
21 export const COLLECTION_CREATE_FORM_NAME = "collectionCreateFormName";
22
23 export const openCollectionCreateDialog = (ownerUuid: string) =>
24     (dispatch: Dispatch) => {
25         dispatch(initialize(COLLECTION_CREATE_FORM_NAME, { ownerUuid }));
26         dispatch(fileUploaderActions.CLEAR_UPLOAD());
27         dispatch(dialogActions.OPEN_DIALOG({ id: COLLECTION_CREATE_FORM_NAME, data: { ownerUuid } }));
28     };
29
30 export const createCollection = (data: CollectionCreateFormDialogData) =>
31     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
32         dispatch(startSubmit(COLLECTION_CREATE_FORM_NAME));
33         try {
34             dispatch(progressIndicatorActions.START_WORKING(COLLECTION_CREATE_FORM_NAME));
35             const newCollection = await services.collectionService.create(data);
36             await dispatch<any>(uploadCollectionFiles(newCollection.uuid));
37             dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_CREATE_FORM_NAME }));
38             dispatch(reset(COLLECTION_CREATE_FORM_NAME));
39             dispatch(progressIndicatorActions.STOP_WORKING(COLLECTION_CREATE_FORM_NAME));
40             return newCollection;
41         } catch (e) {
42             const error = getCommonResourceServiceError(e);
43             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
44                 dispatch(stopSubmit(COLLECTION_CREATE_FORM_NAME, { name: 'Collection with the same name already exists.' }));
45             }
46             dispatch(progressIndicatorActions.STOP_WORKING(COLLECTION_CREATE_FORM_NAME));
47             return;
48         }
49     };