|
|
|
@ -4,6 +4,7 @@ import useIsFirstRender from './useIsFirstRender'; |
|
|
|
|
|
|
|
|
|
const useCookieJar = (): { |
|
|
|
|
cookieJar: CookieJar; |
|
|
|
|
buildCookieJar: () => CookieJar; |
|
|
|
|
getCookie: <T>(key: string) => T | undefined; |
|
|
|
|
getSession: () => SessionCookie | undefined; |
|
|
|
|
getSessionUser: () => SessionCookieUser | undefined; |
|
|
|
@ -12,6 +13,34 @@ const useCookieJar = (): { |
|
|
|
|
|
|
|
|
|
const [cookieJar, setCookieJar] = useState<CookieJar>({}); |
|
|
|
|
|
|
|
|
|
const buildCookieJar = useCallback(() => { |
|
|
|
|
const lines = document.cookie.split(/\s*;\s*/); |
|
|
|
|
|
|
|
|
|
const jar = lines.reduce<CookieJar>((previous, line) => { |
|
|
|
|
const [key, value] = line.split('=', 2); |
|
|
|
|
|
|
|
|
|
const decoded = decodeURIComponent(value); |
|
|
|
|
|
|
|
|
|
let result: unknown; |
|
|
|
|
|
|
|
|
|
if (decoded.startsWith('j:')) { |
|
|
|
|
try { |
|
|
|
|
result = JSON.parse(decoded.substring(2)); |
|
|
|
|
} catch (error) { |
|
|
|
|
result = value; |
|
|
|
|
} |
|
|
|
|
} else { |
|
|
|
|
result = value; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
previous[key] = result; |
|
|
|
|
|
|
|
|
|
return previous; |
|
|
|
|
}, {}); |
|
|
|
|
|
|
|
|
|
return jar; |
|
|
|
|
}, []); |
|
|
|
|
|
|
|
|
|
const getCookie = useCallback( |
|
|
|
|
<T>(key: string, prefix = 'suiapi.') => |
|
|
|
|
cookieJar[`${prefix}${key}`] as T | undefined, |
|
|
|
@ -27,36 +56,13 @@ const useCookieJar = (): { |
|
|
|
|
|
|
|
|
|
useEffect(() => { |
|
|
|
|
if (isFirstRender) { |
|
|
|
|
const lines = document.cookie.split(/\s*;\s*/); |
|
|
|
|
|
|
|
|
|
setCookieJar( |
|
|
|
|
lines.reduce<CookieJar>((previous, line) => { |
|
|
|
|
const [key, value] = line.split('=', 2); |
|
|
|
|
|
|
|
|
|
const decoded = decodeURIComponent(value); |
|
|
|
|
|
|
|
|
|
let result: unknown; |
|
|
|
|
|
|
|
|
|
if (decoded.startsWith('j:')) { |
|
|
|
|
try { |
|
|
|
|
result = JSON.parse(decoded.substring(2)); |
|
|
|
|
} catch (error) { |
|
|
|
|
result = value; |
|
|
|
|
} |
|
|
|
|
} else { |
|
|
|
|
result = value; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
previous[key] = result; |
|
|
|
|
|
|
|
|
|
return previous; |
|
|
|
|
}, {}), |
|
|
|
|
); |
|
|
|
|
setCookieJar(buildCookieJar()); |
|
|
|
|
} |
|
|
|
|
}, [isFirstRender]); |
|
|
|
|
}, [buildCookieJar, isFirstRender]); |
|
|
|
|
|
|
|
|
|
return { |
|
|
|
|
cookieJar, |
|
|
|
|
buildCookieJar, |
|
|
|
|
getCookie, |
|
|
|
|
getSession, |
|
|
|
|
getSessionUser, |
|
|
|
|