import { useCallback } from 'react' ; import { useAuthActions } from 'contexts/auth/AuthContext' ; import { JWT_LOCAL_STORAGE_KEY } from 'contexts/auth/constants' ; import RequestAction from 'hooks/api/_rest/RequestAction' ; import { ApiError } from 'errors/types' ; const baseurl = process . env . NEXT_PUBLIC_API_BASE_URL ?? 'http://localhost:4000' ; const ERR_UNAUTHORIZED = 401 ; type RequestParameters < T > = { body ? : T ; headers ? : Record < string , string > ; unauthorizedErrorHandler ? : ( ) => void ; } ; type GalleryErrorResponseBody = { error ? : string ; } ; export type FetcherType = < ResponseData , RequestBody = Record < string , unknown > > ( path : string , action : RequestAction , parameters ? : RequestParameters < RequestBody > ) => Promise < ResponseData > ; export const _fetch = async ( path , action , parameters = { } ) => { const { body , headers = { } , unauthorizedErrorHandler } = parameters ; const requestOptions = { headers } ; const localJwt = window . localStorage . getItem ( JWT_LOCAL_STORAGE_KEY ) ; const parsedLocalJwt = localJwt && ( JSON . parse ( localJwt ) as string ) ; if ( parsedLocalJwt && requestOptions . headers ) { requestOptions . headers . Authorization = `Bearer ${ parsedLocalJwt }` ; } if ( body ) { requestOptions . method = 'POST' ; requestOptions . body = JSON . stringify ( body ) ; } const response = await fetch ( `${ baseurl }/glry/v1${ path }` , requestOptions ) ; const responseBody = await response . json ( ) . catch ( ( error ) => { if ( response . ok ) { return null ; } if ( action && error instanceof Error ) { throw new ApiError ( error . message , action , response . status ) ; } throw error ; } ) ; if ( ! response . ok ) { if ( response . status === ERR_UNAUTHORIZED ) { unauthorizedErrorHandler ?. ( ) ; } const errorResponseBody = responseBody as GalleryErrorResponseBody ; const serverErrorMessage = errorResponseBody ?. error ?? 'Server Error' ; if ( action ) { throw new ApiError ( serverErrorMessage , action , response . status ) ; } throw new Error ( serverErrorMessage ) ; } return responseBody ; } ; /**
 * You should rarely use this hook directly! Instead:
 * - useGet for fetching
 * - usePost for mutations
 */ export default function useFetcher ( ) { const { logOut } = useAuthActions ( ) ; return useCallback ( async ( path , action , parameters ) => _fetch ( path , action , { ... parameters , unauthorizedErrorHandler : logOut } ) , [ logOut ] ) ; }