refs.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import type { IAttachmentHasId } from '@growi/core';
  2. import type { AxiosError } from 'axios';
  3. import axios from 'axios';
  4. import type { SWRResponse } from 'swr';
  5. // eslint-disable-next-line camelcase
  6. import useSWR, { unstable_serialize } from 'swr';
  7. export const useSWRxRef = (
  8. pagePath: string, fileNameOrId: string, isImmutable?: boolean,
  9. ): SWRResponse<IAttachmentHasId | null, Error> => {
  10. return useSWR(
  11. ['/_api/attachment-refs/ref', pagePath, fileNameOrId, isImmutable],
  12. ([endpoint, pagePath, fileNameOrId]) => {
  13. return axios.get(endpoint, {
  14. params: {
  15. pagePath,
  16. fileNameOrId,
  17. },
  18. }).then(result => result.data.attachment)
  19. .catch(() => null);
  20. },
  21. {
  22. keepPreviousData: true,
  23. revalidateIfStale: !isImmutable,
  24. revalidateOnFocus: !isImmutable,
  25. revalidateOnReconnect: !isImmutable,
  26. },
  27. );
  28. };
  29. export const useSWRxRefs = (
  30. pagePath: string, prefix?: string, options?: Record<string, string | undefined>, isImmutable?: boolean,
  31. ): SWRResponse<IAttachmentHasId[], AxiosError<string>> => {
  32. const serializedOptions = unstable_serialize(options);
  33. return useSWR(
  34. ['/_api/attachment-refs/refs', pagePath, prefix, serializedOptions, isImmutable],
  35. async([endpoint, pagePath, prefix]) => {
  36. return axios.get(endpoint, {
  37. params: {
  38. pagePath,
  39. prefix,
  40. options,
  41. },
  42. }).then(result => result.data.attachments);
  43. },
  44. {
  45. keepPreviousData: true,
  46. revalidateIfStale: !isImmutable,
  47. revalidateOnFocus: !isImmutable,
  48. revalidateOnReconnect: !isImmutable,
  49. },
  50. );
  51. };