# Code coverage report for atlas-mobile-ts/src/hooks/useComments.ts

# All files / atlas-mobile-ts/src/hooks useComments.ts

0% Statements 0/75
0% Branches 0/8
0% Functions 0/12
0% Lines 0/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235

     ﻿/* Copyright (C) Click & Push Accessibility, Inc - All Rights Reserved
     * Unauthorized copying of this file, via any medium is strictly prohibited
     * Proprietary and confidential
     * Written and maintained by the Click & Push Development team
     * <dev@clicknpush.ca>, January 2022
     */

    import axios, { AxiosRequestConfig } from "axios";
    import { QueryClient, useMutation, useQuery, useQueryClient } from "react-query";
    import { authStore } from "../libs/auth/AuthStore";
    import { API_URL, reportAxiosError } from "../utils/RequestUtils";
    import { useAuth } from "./useAuth";

    /**
     * Interface representing a landmark's comment.
     */
    export interface LMComment {
        /**
         * The comment's id.
         */
        id: string,
        /**
         * The id of the user who posted the comment
         */
        poster: string,
        /**
         * The username of the user who posted the comment
         */
         poster_name: string,
        /**
         * The text content of the comment
         */
        content: string
        /**
         * The landmark id that this comment is associated with.
         */
        landmark: string
        /**
         * Timestamp of when the comment was posted.
         */
         timestamp?: Date
        /**
         * Whether or not the comment has been edited.
         */
         edited: boolean
    }

    /**
     * A custom hook containing [react-query]{@link https://react-query.tanstack.com/} queries and mutations and other logic related to interacting with {@link comment} objects.
     * @category Hooks
     * @namespace useComments
     * @param landmarkId - The id of the current landmark focused by the user. Used to fetch only the comments relevant to that landmark.
     */
    export const useComments = (landmarkId: string) => {
        const { refreshAccessToken } = useAuth();

        /**
         * The local instance of the [react-query QueryClient]{@link https://react-query.tanstack.com/reference/QueryClient#_top}.
         * @memberOf useComments
         */
        let queryClient: QueryClient;

        try {
            queryClient = useQueryClient()
        } catch (error) {
            console.error("[CommentsData]: Something went wrong when retrieving query client: " + error)
        }

        /**
         * The callback responsible for retrieving [comments]{@link LMComment} from the API, used by the [react-query useQuery]{@link https://react-query.tanstack.com/reference/useQuery#_top} hook.
         * * @memberOf useComments
         */
        const getCommentsForLandmark = async (landmarkId: string) => {
            Iif (landmarkId) {
                const config: AxiosRequestConfig = {
                    method: 'GET',
                    url: `${API_URL}/api/comments/${landmarkId}`,
                    headers: { "Authorization": "Bearer " + authStore.accessToken, }
                }

                try {
                    const response = await axios(config);
                    return response.data.reverse();
                } catch (error) {
                    Iif (error.response.status == 401) {
                        try {
                            await refreshAccessToken()
                            const response = await axios({...config, headers: { "Authorization": "Bearer " + authStore.accessToken }});
                            return response.data.reverse();
                        } catch (error) {
                            // refreshAccessToken will report errors
                        }
                    }

                    reportAxiosError('Something went wrong when retrieving landmarks', error)
                    throw new Error;
                }
            }
        }

         /**
         * The callback responsible for adding a new {@link Landmark} to the server, used by the [react-query useMutation]{@link https://react-query.tanstack.com/reference/useMutation#_top} hook.
         * * @memberOf useLandmarks
         */
        const createComment = async (commentValue: LMComment): Promise<LMComment | undefined> => {
            Iif (commentValue) {
                const config: AxiosRequestConfig = {
                    method: 'POST',
                    data: commentValue,
                    url: API_URL + `/api/comments/`,
                    headers: { "Authorization": "Bearer " + authStore.accessToken, }
                }

                try {
                    const response = await axios(config);
                    return response.data;
                } catch (error) {
                    Iif (error.response.status == 401) {
                        try {
                            await refreshAccessToken()
                            const response = await axios({...config, headers: { "Authorization": "Bearer " + authStore.accessToken }});

                            return response.data;
                        } catch (error) {
                            // refreshAccessToken will report errors
                        }
                    }

                    reportAxiosError('Something went wrong when retrieving landmarks', error)
                    throw new Error;
                }
            }
        }

        /**
         * The callback responsible for updating a {@link Landmark} on the server, used by the [react-query useMutation]{@link https://react-query.tanstack.com/reference/useMutation#_top} hook.
         * * @memberOf useComments
         */
        const editComment =  async (commentValue: LMComment) => {
            Iif (commentValue) {
                const config: AxiosRequestConfig = {
                    method: 'PUT',
                    data: {...commentValue, edited: true},
                    url: API_URL + `/api/comments/`,
                    headers: { "Authorization": "Bearer " + authStore.accessToken, }
                }

                try {
                    const response = await axios(config);
                    return response.data;
                } catch (error) {
                    Iif (error.response.status == 401) {
                        try {
                            await refreshAccessToken()
                            const response = await axios({...config, headers: { "Authorization": "Bearer " + authStore.accessToken }});

                            return response.data;
                        } catch (error) {
                            // refreshAccessToken will report errors
                        }
                    }

                    reportAxiosError('Something went wrong when retrieving landmarks', error)
                    throw new Error;
                }
            }
        }

        /**
         * The callback responsible for deleting a {@link Landmark} from the server, used by the [react-query useMutation]{@link https://react-query.tanstack.com/reference/useMutation#_top} hook.
         * * @memberOf useLandmarks
         */
        const removeComment =  async (id?: string | null) => {
            Iif (id) {
                const config: AxiosRequestConfig = {
                    method: 'DELETE',
                    url: API_URL + `/api/comments/${id}`,
                    headers: { "Authorization": "Bearer " + authStore.accessToken, }
                }
                try {
                    const response = await axios(config);
                    return response.data;
                } catch (error) {
                    Iif (error.response.status == 401) {
                        try {
                            await refreshAccessToken()

                            // add new access token to header
                            const response = await axios({...config, headers: {"Authorization": "Bearer " + authStore.accessToken}});
                            return response.data;
                        } catch (error) {
                            // refreshAccessToken will report errors
                        }
                    }

                    reportAxiosError('Something went wrong when retrieving landmarks', error)
                    throw new Error;
                }
            }
        }

        // get-all query
        const { data: comments, status: getCommentsForLandmarkStatus, refetch: refetechCommentsForLandmark } = useQuery<LMComment[], Error>(['getCommentsForLandmark', landmarkId], async () => getCommentsForLandmark(landmarkId), {
            placeholderData: () => queryClient.getQueryData('getCommentsForLandmark'),
            staleTime: 1000,
            refetchInterval: 30000,
            refetchOnReconnect: true,
            refetchOnMount: false
        })

        // mutations
        const { status: addCommentStatus, mutateAsync: addCommentAsync, reset: resetAddComment, data: newComment } = useMutation(createComment, {
            onSuccess: data => {
                queryClient.invalidateQueries('getCommentsForLandmark')
            },
        })

        const { status: updateCommentStatus, mutateAsync: updateCommentAsync, reset: resetUpdateComment } = useMutation(editComment, {
            onSuccess: () => queryClient.invalidateQueries('getCommentsForLandmark'),
            onError: () => queryClient.invalidateQueries('getCommentsForLandmark'),
        })

        const { status: deleteCommentStatus, mutateAsync: deleteCommentAsync, reset: resetDeleteComment } = useMutation(removeComment, {
            onSuccess: () => queryClient.invalidateQueries('getCommentsForLandmark'),
            onError: () => queryClient.invalidateQueries('getCommentsForLandmark'),
        })

        return {
            comments, getCommentsForLandmarkStatus, refetechCommentsForLandmark,  //reading
            addCommentAsync, resetAddComment, addCommentStatus, newComment, // creating
            updateCommentAsync, resetUpdateComment, updateCommentStatus, // updating
            deleteCommentAsync, resetDeleteComment, deleteCommentStatus, // deleting
        }
    }