bookmark.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import type { IUser, IPageHasId } from '@growi/core';
  2. import type { SWRResponse } from 'swr';
  3. import useSWR from 'swr';
  4. import useSWRImmutable from 'swr/immutable';
  5. import useSWRMutation, { type SWRMutationResponse } from 'swr/mutation';
  6. import { apiv3Get } from '../client/util/apiv3-client';
  7. import type { IBookmarkInfo } from '../interfaces/bookmark-info';
  8. import { useCurrentUser } from './context';
  9. export const useSWRxBookmarkedUsers = (pageId: string | null): SWRResponse<IUser[], Error> => {
  10. return useSWR(
  11. pageId != null ? `/bookmarks/info?pageId=${pageId}` : null,
  12. endpoint => apiv3Get<IBookmarkInfo>(endpoint).then(response => response.data.bookmarkedUsers),
  13. );
  14. };
  15. export const useSWRxUserBookmarks = (userId: string | null): SWRResponse<(IPageHasId | null)[], Error> => {
  16. return useSWRImmutable(
  17. userId != null ? `/bookmarks/${userId}` : null,
  18. endpoint => apiv3Get(endpoint).then((response) => {
  19. const { userRootBookmarks } = response.data;
  20. return userRootBookmarks.map(item => item.page); // page will be null if the page is deleted
  21. }),
  22. );
  23. };
  24. export const useSWRMUTxCurrentUserBookmarks = (): SWRMutationResponse<(IPageHasId | null)[], Error> => {
  25. const { data: currentUser } = useCurrentUser();
  26. return useSWRMutation(
  27. currentUser != null ? `/bookmarks/${currentUser?._id}` : null,
  28. endpoint => apiv3Get(endpoint).then((response) => {
  29. const { userRootBookmarks } = response.data;
  30. return userRootBookmarks.map(item => item.page); // page will be null if the page is deleted
  31. }),
  32. );
  33. };