comment.tsx 1.7 KB

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