1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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";
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>>()
18 export type FavoritesAction = UnionOf<typeof favoritesActions>;
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 });
32 dispatch(favoritesActions.UPDATE_FAVORITES({ [resource.uuid]: !isFavorite }));
33 dispatch(snackbarActions.CLOSE_SNACKBAR());
34 dispatch(snackbarActions.OPEN_SNACKBAR({
36 ? "Removed from favorites"
37 : "Added to favorites",
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));