comment.tsx 1.9 KB

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