bookmark.ts 1.7 KB

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