comment.tsx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { useCallback } from 'react';
  2. import type { Nullable } from '@growi/core';
  3. import type { SWRResponse } from 'swr';
  4. import useSWR from 'swr';
  5. import { apiGet, apiPost } from '~/client/util/apiv1-client';
  6. import type { ICommentHasIdList, ICommentPostArgs } from '../interfaces/comment';
  7. type IResponseComment = {
  8. comments: ICommentHasIdList,
  9. ok: boolean,
  10. }
  11. type CommentOperation = {
  12. update(comment: string, revisionId: string, commentId: string): Promise<void>,
  13. post(args: ICommentPostArgs): Promise<void>
  14. }
  15. export const useSWRxPageComment = (pageId: Nullable<string>): SWRResponse<ICommentHasIdList, Error> & CommentOperation => {
  16. const shouldFetch: boolean = pageId != null;
  17. const swrResponse = useSWR(
  18. shouldFetch ? ['/comments.get', pageId] : null,
  19. ([endpoint, pageId]) => apiGet(endpoint, { page_id: pageId }).then((response:IResponseComment) => response.comments),
  20. );
  21. const { mutate } = swrResponse;
  22. const update = useCallback(async(comment: string, revisionId: string, commentId: string) => {
  23. await apiPost('/comments.update', {
  24. commentForm: {
  25. comment,
  26. revision_id: revisionId,
  27. comment_id: commentId,
  28. },
  29. });
  30. mutate();
  31. }, [mutate]);
  32. const post = useCallback(async(args: ICommentPostArgs) => {
  33. const { commentForm, slackNotificationForm } = args;
  34. const { comment, revisionId, replyTo } = commentForm;
  35. const { isSlackEnabled, slackChannels } = slackNotificationForm;
  36. await apiPost('/comments.add', {
  37. commentForm: {
  38. comment,
  39. page_id: pageId,
  40. revision_id: revisionId,
  41. replyTo,
  42. },
  43. slackNotificationForm: {
  44. isSlackEnabled,
  45. slackChannels,
  46. },
  47. });
  48. mutate();
  49. }, [mutate, pageId]);
  50. return {
  51. ...swrResponse,
  52. update,
  53. post,
  54. };
  55. };