cr changes
[arvados.git] / src / store / favorites / favorites-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { unionize, ofType, UnionOf } from "~/common/unionize";
6 import { Dispatch } from "redux";
7 import { RootState } from "../store";
8 import { checkFavorite } from "./favorites-reducer";
9 import { snackbarActions } from "../snackbar/snackbar-actions";
10 import { ServiceRepository } from "~/services/services";
11
12 export const favoritesActions = unionize({
13     TOGGLE_FAVORITE: ofType<{ resourceUuid: string }>(),
14     CHECK_PRESENCE_IN_FAVORITES: ofType<string[]>(),
15     UPDATE_FAVORITES: ofType<Record<string, boolean>>()
16 });
17
18 export type FavoritesAction = UnionOf<typeof favoritesActions>;
19
20 export const toggleFavorite = (resource: { uuid: string; name: string }) =>
21     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<any> => {
22         const userUuid = getState().auth.user!.uuid;
23         dispatch(favoritesActions.TOGGLE_FAVORITE({ resourceUuid: resource.uuid }));
24         dispatch(snackbarActions.OPEN_SNACKBAR({ message: "Working..." }));
25         const isFavorite = checkFavorite(resource.uuid, getState().favorites);
26         const promise: any = isFavorite
27             ? services.favoriteService.delete({ userUuid, resourceUuid: resource.uuid })
28             : services.favoriteService.create({ userUuid, resource });
29
30         return promise
31             .then(() => {
32                 dispatch(favoritesActions.UPDATE_FAVORITES({ [resource.uuid]: !isFavorite }));
33                 dispatch(snackbarActions.CLOSE_SNACKBAR());
34                 dispatch(snackbarActions.OPEN_SNACKBAR({
35                     message: isFavorite
36                         ? "Removed from favorites"
37                         : "Added to favorites",
38                     hideDuration: 2000
39                 }));
40             });
41     };
42
43 export const updateFavorites = (resourceUuids: string[]) =>
44     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
45         const userUuid = getState().auth.user!.uuid;
46         dispatch(favoritesActions.CHECK_PRESENCE_IN_FAVORITES(resourceUuids));
47         services.favoriteService
48             .checkPresenceInFavorites(userUuid, resourceUuids)
49             .then((results: any) => {
50                 dispatch(favoritesActions.UPDATE_FAVORITES(results));
51             });
52     };