attachment.tsx 1.6 KB

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