attachment.tsx 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { useCallback } from 'react';
  2. import {
  3. IAttachmentHasId, Nullable, type SWRResponseWithUtils, withUtils,
  4. } from '@growi/core';
  5. import useSWR from 'swr';
  6. import { apiPost } from '~/client/util/apiv1-client';
  7. import { apiv3Get } from '~/client/util/apiv3-client';
  8. import { IResAttachmentList } from '~/interfaces/attachment';
  9. type Util = {
  10. remove(body: { attachment_id: string }): Promise<void>
  11. };
  12. type IDataAttachmentList = {
  13. attachments: (IAttachmentHasId)[]
  14. totalAttachments: number
  15. limit: number
  16. };
  17. export const useSWRxAttachments = (pageId?: Nullable<string>, pageNumber?: number): SWRResponseWithUtils<Util, IDataAttachmentList, Error> => {
  18. const shouldFetch = pageId != null && pageNumber != null;
  19. const fetcher = useCallback(async([endpoint, pageId, pageNumber]) => {
  20. const res = await apiv3Get<IResAttachmentList>(endpoint, { pageId, pageNumber });
  21. const resAttachmentList = res.data;
  22. const { paginateResult } = resAttachmentList;
  23. return {
  24. attachments: paginateResult.docs,
  25. totalAttachments: paginateResult.totalDocs,
  26. limit: paginateResult.limit,
  27. };
  28. }, []);
  29. const swrResponse = useSWR(
  30. shouldFetch ? ['/attachment/list', pageId, pageNumber] : null,
  31. fetcher,
  32. );
  33. // Utils
  34. const remove = useCallback(async(body: { attachment_id: string }) => {
  35. const { mutate } = swrResponse;
  36. try {
  37. await apiPost('/attachments.remove', body);
  38. mutate();
  39. }
  40. catch (err) {
  41. throw err;
  42. }
  43. }, [swrResponse]);
  44. return withUtils<Util, IDataAttachmentList, Error>(swrResponse, { remove });
  45. };