# All files / atlas/src/hooks useLandmarks.ts

20.9% Statements 14/67
0% Branches 0/8
16.67% Functions 2/12
21.21% Lines 14/66

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
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266

    6x
    6x

    6x
    6x

    6x

    6x

    6x

    6x

    6x
    12x

    6x

    6x

    6x

    6x

     // This file houses crud methods to interact with landmarks on the server. They are generally called by react query mutations.

    import axios, { AxiosRequestConfig } from "axios"
    import { Region } from "react-native-maps";
    import { QueryClient, useMutation, useQuery, useQueryClient } from "react-query";
    import { API_URL, reportAxiosError as reportAxiosError } from "../globals"
    import { authStore } from "../stores/AuthStore";
    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 text content of the comment
         */
        text: string
        /**
         * The landmark that this comment is associated with.
         */
        landmark: Landmark
    }

    /**
     * Interface representing a landmark object
     */
    export interface Landmark {
        /**
         * The id of the landmark.
         */
        id?: string | null,
        /**
         * The rating of the landmark.
         */
        rating?: number | null,
        /**
         * The id of the user who created the landmark.
         */
        user?: string | null,
        /**
         * The longitude of the landmark's location.
         */
        longitude?: number | null,
        /**
         * The latitude of the landmark's location.
         */
        latitude?: number | null,
        /**
         * The landmark's title.
         */
        title?: string | null,
        /**
         * The landmark's description.
         */
        description?: string | null,
        /**
         * User [comments]{@link LMComment} associated with this landmark.
         */
        comments?: LMComment[] | null,
        /**
         * An integer representing the type of this landmark.
         */
        landmark_type?: number | null, // for working with existing database schema, should be changed
        /**
         * A Date object representing when this landmark was created.
         */
        time?: Date | null
    }

    /**
     * A custom hook containing [react-query]{@link https://react-query.tanstack.com/} queries and mutations and other logic related to interacting with {@link Landmark} objects.
     * @category Hooks
     * @namespace useLandmarks
     */
    export const useLandmarks = (region: Region | undefined) => {
        const { refreshAccessToken } = useAuth();

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

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

        /**
         * The callback responsible for retrieving {@link Landmark} from the API, used by the [react-query useQuery]{@link https://react-query.tanstack.com/reference/useQuery#_top} hook.
         * * @memberOf useLandmarks
         */
        const getLandmarks = async (region: Region | undefined) => {
            // if (region) {
                const config: AxiosRequestConfig = {
                method: 'GET',
                // url: `${API_URL}/api/landmarks/?lat=${region.latitude}&long=${region.longitude}&lat_delta=${region.latitudeDelta}&long_delta=${region.longitudeDelta}`,
                url: `${API_URL}/api/landmarks/`,
                headers: { "Authorization": "Bearer " + authStore.accessToken, }
            }

            try {
                const response = await axios(config);
                return response.data;
            } catch (error) {
                if (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;
            }
            // }
            // else {
            //     return [];
            // }
        }

         /**
         * 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 createLandmark = async (landmarkValue: Landmark | undefined): Promise<Landmark | undefined> => {
            const config: AxiosRequestConfig = {
                method: 'POST',
                data: landmarkValue,
                url: API_URL + `/api/landmark/`,
                headers: { "Authorization": "Bearer " + authStore.accessToken, }
            }

            try {
                const response = await axios(config);
                return response.data;
            } catch (error) {
                if (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 useLandmarks
         */
        const editLandmark =  async (landmarkValue: Landmark) => {
            const config: AxiosRequestConfig = {
                method: 'PUT',
                data: landmarkValue,
                url: API_URL + `/api/landmark/`,
                headers: { "Authorization": "Bearer " + authStore.accessToken, }
            }

            console.log(landmarkValue)

            try {
                const response = await axios(config);
                return response.data;
            } catch (error) {
                if (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 removeLandmark =  async (id?: string | null) => {
            const config: AxiosRequestConfig = {
                method: 'DELETE',
                url: API_URL + `/api/landmark/${id}`,
                headers: { "Authorization": "Bearer " + authStore.accessToken, }
            }
            try {
                const response = await axios(config);
                return response.data;
            } catch (error) {
                if (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: landmarks, status: getLandmarksStatus, refetch: refetchLandmarks } = useQuery<Landmark[], Error>(['getLandmarks', region], () => getLandmarks(region), {
            placeholderData: () => queryClient.getQueryData('getLandmarks'),
            staleTime: 1000,
            refetchInterval: 30000,
            refetchOnReconnect: true,
            refetchOnMount: false
        })

        // mutations
        const { status: addLandmarkStatus, mutateAsync: addLandmarkAsync, reset: resetAddLm, data: newLandmark } = useMutation(createLandmark, {
            onSuccess: data => {
                queryClient.invalidateQueries('getLandmarks')
            },
        })

        const { status: updateLandmarkStatus, mutateAsync: updateLandmark, reset: resetUpdateLm } = useMutation(editLandmark, {
            onSuccess: () => queryClient.invalidateQueries('getLandmarks'),
            onError: () => queryClient.invalidateQueries('getLandmarks'),
        })

        const { status: deleteLandmarkStatus, mutateAsync: deleteLandmark, reset: resetDeleteLm } = useMutation(removeLandmark, {
            onSuccess: () => queryClient.invalidateQueries('getLandmarks'),
            onError: () => queryClient.invalidateQueries('getLandmarks'),
        })

        return {
            landmarks, getLandmarksStatus, refetchLandmarks,  //reading
            addLandmarkAsync, resetAddLm, addLandmarkStatus, newLandmark, // creating
            updateLandmark, resetUpdateLm, updateLandmarkStatus, // updating
            deleteLandmark, resetDeleteLm, deleteLandmarkStatus, // deleting
        }
    }