swr-initor.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. 'use client'
  2. import { SWRConfig } from 'swr'
  3. import { useCallback, useEffect, useState } from 'react'
  4. import type { ReactNode } from 'react'
  5. import { usePathname, useRouter, useSearchParams } from 'next/navigation'
  6. import { fetchSetupStatus } from '@/service/common'
  7. type SwrInitorProps = {
  8. children: ReactNode
  9. }
  10. const SwrInitor = ({
  11. children,
  12. }: SwrInitorProps) => {
  13. const router = useRouter()
  14. const searchParams = useSearchParams()
  15. const consoleToken = decodeURIComponent(searchParams.get('access_token') || '')
  16. const refreshToken = decodeURIComponent(searchParams.get('refresh_token') || '')
  17. const consoleTokenFromLocalStorage = localStorage?.getItem('console_token')
  18. const refreshTokenFromLocalStorage = localStorage?.getItem('refresh_token')
  19. const pathname = usePathname()
  20. const [init, setInit] = useState(false)
  21. const isSetupFinished = useCallback(async () => {
  22. try {
  23. if (localStorage.getItem('setup_status') === 'finished')
  24. return true
  25. const setUpStatus = await fetchSetupStatus()
  26. if (setUpStatus.step !== 'finished') {
  27. localStorage.removeItem('setup_status')
  28. return false
  29. }
  30. localStorage.setItem('setup_status', 'finished')
  31. return true
  32. }
  33. catch (error) {
  34. console.error(error)
  35. return false
  36. }
  37. }, [])
  38. useEffect(() => {
  39. (async () => {
  40. try {
  41. const isFinished = await isSetupFinished()
  42. if (!isFinished) {
  43. router.replace('/install')
  44. return
  45. }
  46. if (!((consoleToken && refreshToken) || (consoleTokenFromLocalStorage && refreshTokenFromLocalStorage))) {
  47. router.replace('/signin')
  48. return
  49. }
  50. if (searchParams.has('access_token') || searchParams.has('refresh_token')) {
  51. consoleToken && localStorage.setItem('console_token', consoleToken)
  52. refreshToken && localStorage.setItem('refresh_token', refreshToken)
  53. router.replace(pathname)
  54. }
  55. setInit(true)
  56. }
  57. catch (error) {
  58. router.replace('/signin')
  59. }
  60. })()
  61. }, [isSetupFinished, router, pathname, searchParams, consoleToken, refreshToken, consoleTokenFromLocalStorage, refreshTokenFromLocalStorage])
  62. return init
  63. ? (
  64. <SWRConfig value={{
  65. shouldRetryOnError: false,
  66. revalidateOnFocus: false,
  67. }}>
  68. {children}
  69. </SWRConfig>
  70. )
  71. : null
  72. }
  73. export default SwrInitor