11import config from "config" ;
22import { Cookies } from "react-cookie" ;
3+ import { STATUS_UNAUTHORIZED } from "./constants" ;
34
45export type Query = Record < string , any > ;
56
@@ -100,8 +101,6 @@ const callApi = async <T>(
100101 API_ROOT = API_ROOT . slice ( 0 , API_ROOT . length - 1 ) ;
101102 }
102103
103- console . info ( "api.api: API_ROOT:" , API_ROOT , "paramsAPIRoot:" , paramsAPIRoot ) ;
104-
105104 let theEndpoint = endpoint ;
106105 if ( ! theEndpoint . includes ( API_ROOT ) ) {
107106 theEndpoint = `${ API_ROOT } ${ endpoint } ` ;
@@ -166,6 +165,29 @@ const postFile = async <T>(
166165 ) ;
167166} ;
168167
168+ const getCurrentPathQeury = ( ) => {
169+ const searchStr = getCurrentPathQeurySanitizeSearch ( window . location . search ) ;
170+ return `${ window . location . pathname } ${ searchStr } ` ;
171+ } ;
172+
173+ const getCurrentPathQeurySanitizeSearch = ( search : string ) => {
174+ if ( ! search ) {
175+ return "" ;
176+ }
177+
178+ // if with only '?': remove '?'
179+ if ( search [ 0 ] === "?" && search . length === 1 ) {
180+ return "" ;
181+ }
182+
183+ // if not starting with '?': add '?'
184+ if ( search [ 0 ] !== "?" ) {
185+ return `?${ search } ` ;
186+ }
187+
188+ return search ;
189+ } ;
190+
169191const fetchCore = async < T > (
170192 endpoint : string ,
171193 options : RequestInit ,
@@ -177,6 +199,11 @@ const fetchCore = async <T>(
177199 return res
178200 . json ( )
179201 . then ( ( collectionJsonData ) => {
202+ if ( res . status === STATUS_UNAUTHORIZED ) {
203+ const redirectTo = encodeURIComponent ( getCurrentPathQeury ( ) ) ;
204+ window . location . href = `/login?redirectTo=${ redirectTo } ` ;
205+ }
206+
180207 if ( res . status >= 400 ) {
181208 const msg = collectionJsonData . error ;
182209 return { status, errmsg : msg } ;
0 commit comments