comment.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 {
  7. ICommentHasIdList,
  8. ICommentPostArgs,
  9. } from '../interfaces/comment';
  10. type IResponseComment = {
  11. comments: ICommentHasIdList;
  12. ok: boolean;
  13. };
  14. type CommentOperation = {
  15. update(comment: string, revisionId: string, commentId: string): Promise<void>;
  16. post(args: ICommentPostArgs): Promise<void>;
  17. };
  18. export const useSWRxPageComment = (
  19. pageId: Nullable<string>,
  20. ): SWRResponse<ICommentHasIdList, Error> & CommentOperation => {
  21. const shouldFetch: boolean = pageId != null;
  22. const swrResponse = useSWR(
  23. shouldFetch ? ['/comments.get', pageId] : null,
  24. ([endpoint, pageId]) =>
  25. apiGet(endpoint, { page_id: pageId }).then(
  26. (response: IResponseComment) => response.comments,
  27. ),
  28. );
  29. const { mutate } = swrResponse;
  30. const update = useCallback(
  31. async (comment: string, revisionId: string, commentId: string) => {
  32. await apiPost('/comments.update', {
  33. commentForm: {
  34. comment,
  35. revision_id: revisionId,
  36. comment_id: commentId,
  37. },
  38. });
  39. mutate();
  40. },
  41. [mutate],
  42. );
  43. const post = useCallback(
  44. async (args: ICommentPostArgs) => {
  45. const { commentForm, slackNotificationForm } = args;
  46. const { comment, revisionId, replyTo } = commentForm;
  47. const { isSlackEnabled, slackChannels } = slackNotificationForm;
  48. await apiPost('/comments.add', {
  49. commentForm: {
  50. comment,
  51. page_id: pageId,
  52. revision_id: revisionId,
  53. replyTo,
  54. },
  55. slackNotificationForm: {
  56. isSlackEnabled,
  57. slackChannels,
  58. },
  59. });
  60. mutate();
  61. },
  62. [mutate, pageId],
  63. );
  64. return {
  65. ...swrResponse,
  66. update,
  67. post,
  68. };
  69. };