Fix import
[arvados-workbench2.git] / src / store / favorites / favorites-actions.ts
index d7e14a2bfbc2f7898f8f7438122ca92dbcd480de..225c9b35c36ce934721c1c10f5cb2883a15e4594 100644 (file)
@@ -3,18 +3,37 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import { unionize, ofType, UnionOf } from "unionize";
-import { Dispatch } from "../../../node_modules/redux";
+import { Dispatch } from "redux";
 import { favoriteService } from "../../services/services";
+import { RootState } from "../store";
+import { checkFavorite } from "./favorites-reducer";
 
 export const favoritesActions = unionize({
+    TOGGLE_FAVORITE: ofType<{ resourceUuid: string }>(),
     CHECK_PRESENCE_IN_FAVORITES: ofType<string[]>(),
     UPDATE_FAVORITES: ofType<Record<string, boolean>>()
 }, { tag: 'type', value: 'payload' });
 
 export type FavoritesAction = UnionOf<typeof favoritesActions>;
 
-export const checkPresenceInFavorites = (userUuid: string, resourceUuids: string[]) =>
-    (dispatch: Dispatch) => {
+export const toggleFavorite = (resource: { uuid: string; name: string }) =>
+    (dispatch: Dispatch, getState: () => RootState) => {
+        const userUuid = getState().auth.user!.uuid;
+        dispatch(favoritesActions.TOGGLE_FAVORITE({ resourceUuid: resource.uuid }));
+        const isFavorite = checkFavorite(resource.uuid, getState().favorites);
+        const promise = isFavorite
+            ? favoriteService.delete({ userUuid, resourceUuid: resource.uuid })
+            : favoriteService.create({ userUuid, resource });
+
+        promise
+            .then(fav => {
+                dispatch(favoritesActions.UPDATE_FAVORITES({ [resource.uuid]: !isFavorite }));
+            });
+    };
+
+export const checkPresenceInFavorites = (resourceUuids: string[]) =>
+    (dispatch: Dispatch, getState: () => RootState) => {
+        const userUuid = getState().auth.user!.uuid;
         dispatch(favoritesActions.CHECK_PRESENCE_IN_FAVORITES(resourceUuids));
         favoriteService
             .checkPresenceInFavorites(userUuid, resourceUuids)