1+ import { GET_COMMENTS_OF_A_POST } from './types'
2+ import { errorHandler } from '../utils/errorHandler'
3+ import axios from 'axios'
4+ import { setRequestStatus } from '../utils/setRequestStatus'
5+
6+ // CREATE COMMENT ON A PARTICULAR POST
7+ export const createComment = ( postId , comment ) => async ( dispatch ) => {
8+ try {
9+ const res = await axios . post ( `/comment/${ postId } ` , comment )
10+ dispatch ( setRequestStatus ( false ) ) ;
11+ if ( res . status === 201 ) {
12+ dispatch ( setRequestStatus ( true ) )
13+ console . log ( 'created comment ' , res . data . comment )
14+ dispatch ( getAllCommentsOfPost ( ) ) ;
15+ }
16+ } catch ( error ) {
17+ dispatch ( errorHandler ( error ) )
18+ }
19+ }
20+
21+ // GET ALL COMMENTS OF A POST
22+ export const getAllCommentsOfPost = ( postId ) => async ( dispatch ) => {
23+ try {
24+ const res = await axios . get ( `/comment/${ postId } ` )
25+ dispatch ( setRequestStatus ( false ) )
26+ if ( res . status === 200 ) {
27+ dispatch ( setRequestStatus ( true ) ) ;
28+ console . log ( 'fetching comments of ' , postId , res . data . comments ) ;
29+ dispatch ( {
30+ type : GET_COMMENTS_OF_A_POST ,
31+ payload : res . data . comments
32+ } )
33+ }
34+ } catch ( error ) {
35+ dispatch ( errorHandler ( error ) )
36+ }
37+ }
38+
39+ // UPDATE COMMENT OF A POST
40+ export const updateComment = ( commentId , updatedComment ) => async ( dispatch ) => {
41+ try {
42+ const res = await axios . patch ( `/comment/${ commentId } ` , updatedComment )
43+ dispatch ( setRequestStatus ( false ) )
44+ if ( res . status === 200 ) {
45+ dispatch ( setRequestStatus ( true ) )
46+ console . log ( 'comment updated ' , res . data . comment )
47+ dispatch ( getAllCommentsOfPost ( ) )
48+ }
49+ } catch ( error ) {
50+ errorHandler ( error )
51+ }
52+ }
53+
54+ // DELETE COMMENT
55+ export const deleteComment = ( commentId ) => async ( dispatch ) => {
56+ try {
57+ const res = await axios . delete ( `/comment/${ commentId } ` )
58+ dispatch ( setRequestStatus ( false ) )
59+ if ( res . status === 200 ) {
60+ dispatch ( setRequestStatus ( true ) ) ;
61+ console . log ( 'comment deleted ' , res . data )
62+ dispatch ( getAllCommentsOfPost ( ) )
63+ }
64+ } catch ( error ) {
65+ dispatch ( errorHandler ( error ) )
66+ }
67+ }
0 commit comments