diff options
Diffstat (limited to 'src/services/CommentService.ts')
-rw-r--r-- | src/services/CommentService.ts | 101 |
1 files changed, 101 insertions, 0 deletions
diff --git a/src/services/CommentService.ts b/src/services/CommentService.ts new file mode 100644 index 00000000..3baf0305 --- /dev/null +++ b/src/services/CommentService.ts @@ -0,0 +1,101 @@ +import AsyncStorage from '@react-native-community/async-storage'; +import {Alert} from 'react-native'; +import {COMMENTS_ENDPOINT, COMMENT_THREAD_ENDPOINT} from '../constants'; +import {ERROR_FAILED_TO_COMMENT} from '../constants/strings'; +import {CommentType} from '../types'; + +export const getComments = async ( + objectId: string, + fetchThreads: boolean, +): Promise<CommentType[]> => { + let comments: CommentType[] = []; + try { + const token = await AsyncStorage.getItem('token'); + const endpoint = fetchThreads + ? COMMENT_THREAD_ENDPOINT + '?comment_id=' + : COMMENTS_ENDPOINT + '?moment_id='; + const response = await fetch(endpoint + objectId, { + method: 'GET', + headers: { + Authorization: 'Token ' + token, + }, + }); + const status = response.status; + if (status === 200) { + comments = await response.json(); + console.log(comments[0]); + } else { + console.log('Could not load comments'); + } + } catch (error) { + console.log('Could not load comments', error); + } + return comments; +}; + +export const postComment = async ( + comment: string, + objectId: string, + postThread: boolean, +) => { + try { + const token = await AsyncStorage.getItem('token'); + const request = new FormData(); + request.append('comment', comment); + if (postThread) { + request.append('comment_id', objectId); + } else { + request.append('moment_id', objectId); + } + const endpoint = postThread ? COMMENT_THREAD_ENDPOINT : COMMENTS_ENDPOINT; + const response = await fetch(endpoint, { + method: 'POST', + headers: { + Authorization: 'Token ' + token, + }, + body: request, + }); + if (response.status !== 200) { + throw 'server error'; + } + return await response.json(); + } catch (error) { + Alert.alert(ERROR_FAILED_TO_COMMENT); + return undefined; + } +}; + +//Get count of comments for a moment +export const getCommentsCount = async ( + objectId: string, + fetchThread: boolean, +): Promise<string> => { + let comments_count: string = ''; + try { + const token = await AsyncStorage.getItem('token'); + const endpoint = fetchThread ? COMMENT_THREAD_ENDPOINT : COMMENTS_ENDPOINT; + const response = await fetch(endpoint + `${objectId}/`, { + method: 'GET', + headers: { + Authorization: 'Token ' + token, + }, + }); + const status = response.status; + if (status === 200) { + const response_data = await response.json(); + comments_count = response_data.count; + } else { + console.log( + 'Something went wrong! ðŸ˜', + 'Not able to retrieve comments count', + ); + } + } catch (error) { + console.log( + 'Something went wrong! ðŸ˜', + 'Not able to retrieve comments count', + error, + ); + } + return comments_count; +}; |