Merge branch '14102-actions-repository'
[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 { uploadCollectionFiles } from '~/store/collections/uploader/collection-uploader-actions';
9 import { dialogActions } from "~/store/dialog/dialog-actions";
10 import { CollectionResource } from '~/models/collection';
11 import { ServiceRepository } from '~/services/services';
12 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/common/api/common-resource-service";
13
14 export interface CollectionCreateFormDialogData {
15     ownerUuid: string;
16     name: string;
17     description: string;
18     files: File[];
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(dialogActions.OPEN_DIALOG({ id: COLLECTION_CREATE_FORM_NAME, data: { ownerUuid } }));
27     };
28
29 export const createCollection = (collection: Partial<CollectionResource>) =>
30     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
31         dispatch(startSubmit(COLLECTION_CREATE_FORM_NAME));
32         try {
33             const newCollection = await services.collectionService.create(collection);
34             await dispatch<any>(uploadCollectionFiles(newCollection.uuid));
35             dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_CREATE_FORM_NAME }));
36             dispatch(reset(COLLECTION_CREATE_FORM_NAME));
37             return newCollection;
38         } catch (e) {
39             const error = getCommonResourceServiceError(e);
40             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
41                 dispatch(stopSubmit(COLLECTION_CREATE_FORM_NAME, { name: 'Collection with the same name already exists.' }));
42             }
43             return ;
44         }
45     };