attachment.tsx 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { useCallback } from 'react';
  2. import type {
  3. IAttachmentHasId, Nullable,
  4. } from '@growi/core';
  5. import {
  6. type SWRResponseWithUtils, withUtils,
  7. } from '@growi/core/dist/swr';
  8. import { Util } from 'reactstrap';
  9. import useSWR, { useSWRConfig } from 'swr';
  10. import { apiPost } from '~/client/util/apiv1-client';
  11. import { apiv3Get } from '~/client/util/apiv3-client';
  12. import { IResAttachmentList } from '~/interfaces/attachment';
  13. type Util = {
  14. remove(body: { attachment_id: string }): Promise<void>
  15. };
  16. type IDataAttachmentList = {
  17. attachments: IAttachmentHasId[]
  18. totalAttachments: number
  19. limit: number
  20. };
  21. export const useSWRxAttachment = (attachmentId: string): SWRResponseWithUtils<Util, IAttachmentHasId, Error> => {
  22. const swrResponse = useSWR(
  23. [`/attachment/${attachmentId}`],
  24. useCallback(async([endpoint]) => {
  25. const res = await apiv3Get(endpoint);
  26. return res.data.attachment;
  27. }, []),
  28. );
  29. // Utils
  30. const remove = useCallback(async(body: { attachment_id: string }) => {
  31. try {
  32. await apiPost('/attachments.remove', body);
  33. swrResponse.mutate(body.attachment_id);
  34. }
  35. catch (err) {
  36. throw err;
  37. }
  38. }, [swrResponse]);
  39. return withUtils<Util, IAttachmentHasId, Error>(swrResponse, { remove });
  40. };
  41. export const useSWRxAttachments = (pageId?: Nullable<string>, pageNumber?: number): SWRResponseWithUtils<Util, IDataAttachmentList, Error> => {
  42. const { mutate: mutateUseSWRxAttachment } = useSWRConfig();
  43. const shouldFetch = pageId != null && pageNumber != null;
  44. const fetcher = useCallback(async([endpoint, pageId, pageNumber]) => {
  45. const res = await apiv3Get<IResAttachmentList>(endpoint, { pageId, pageNumber });
  46. const resAttachmentList = res.data;
  47. const { paginateResult } = resAttachmentList;
  48. return {
  49. attachments: paginateResult.docs,
  50. totalAttachments: paginateResult.totalDocs,
  51. limit: paginateResult.limit,
  52. };
  53. }, []);
  54. const swrResponse = useSWR(
  55. shouldFetch ? ['/attachment/list', pageId, pageNumber] : null,
  56. fetcher,
  57. );
  58. // Utils
  59. const remove = useCallback(async(body: { attachment_id: string }) => {
  60. const { mutate } = swrResponse;
  61. try {
  62. await apiPost('/attachments.remove', body);
  63. mutate();
  64. // Mutation for rich attachment rendering
  65. mutateUseSWRxAttachment([`/attachment/${body.attachment_id}`], body.attachment_id);
  66. }
  67. catch (err) {
  68. throw err;
  69. }
  70. }, [mutateUseSWRxAttachment, swrResponse]);
  71. return withUtils<Util, IDataAttachmentList, Error>(swrResponse, { remove });
  72. };