feat: 完成 useStorage

feature/price_manager
Jimmy Liow 1 year ago
parent 3235e7e574
commit e31a20e92d

@ -1,22 +1,38 @@
const persistObject = {}
/**
* GH-INT:USER_ID -> userId = 456
* GH-STR:LOGIN_TOKEN -> loginToken = 'E6779386E7D64DF0ADD0F97767E00D8B'
*/
export function useStorage() {
const setSession = (key, value) => {
if (window.sessionStorage) {
const sessionStorage = window.sessionStorage
return sessionStorage.setItem(key, value)
const getStorage = () => {
if (import.meta.env.DEV && window.localStorage) {
return window.localStorage
} else if (window.sessionStorage) {
return window.sessionStorage
} else {
console.error('browser not support sessionStorage.')
console.error('browser not support localStorage and sessionStorage.')
}
}
const setProperty = (key, value) => {
const webStorage = getStorage()
const typeAndKey = key.split(':')
if (typeAndKey.length === 2) {
const propName = camelCasedWords(typeAndKey[1])
persistObject[propName] = value
webStorage.setItem(key, value)
}
}
// USER_ID -> userId
const camelCasedWords = (string) => {
if (typeof string !== 'string' || string.length === 0) {
return string;
}
return string.split('_').map((word, index) => {
if (index === 0) {
return ''
} else if (index === 1) {
return word.toLowerCase()
} else {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
@ -24,27 +40,34 @@ export function useStorage() {
}).join('')
}
const storageObject = {}
if (Object.keys(persistObject).length == 0) {
if (window.sessionStorage) {
const webStorage = getStorage()
const sessionStorage = window.sessionStorage
for (let i = 0; i < webStorage.length; i++) {
const key = webStorage.key(i)
const typeAndKey = key.split(':')
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i)
const value = sessionStorage.getItem(key)
const propName = camelCasedWords(key)
storageObject[propName] = value
if (typeAndKey.length === 2) {
const value = webStorage.getItem(key)
const propName = camelCasedWords(typeAndKey[1])
if (typeAndKey[0] === 'GH-INT') {
persistObject[propName] = parseInt(value, 10)
} else {
persistObject[propName] = value
}
}
}
}
return {
...storageObject,
...persistObject,
setStorage: (key, value) => {
setSession(key, value)
setProperty(key, value)
},
clearStorage: () => {
getStorage().clear()
Object.assign(persistObject, {})
}
}
} else {
console.error('browser not support sessionStorage.')
return {}
}
}

@ -11,6 +11,7 @@ import "@/assets/global.css";
import App from "@/views/App";
import Standlone from "@/views/Standlone";
import Login from "@/views/Login";
import Logout from "@/views/Logout";
import Index from "@/views/index";
import ErrorPage from "@/views/error-page";
import ReservationNewest from "@/views/reservation/Newest";
@ -66,6 +67,7 @@ const router = createBrowserRouter([
element: <Standlone />,
children: [
{ path: "/login", element: <Login /> },
{ path: "/logout", element: <Logout /> },
]
}
]);

@ -1,15 +1,15 @@
import { makeAutoObservable, runInAction } from "mobx";
import { create } from 'zustand'
import { appendRequestParams, fetchJSON, postForm } from '@/utils/request';
import { HT_HOST } from "@/config";
import { isNotEmpty, prepareUrl } from '@/utils/commons';
import { loadPageSpy } from '@/pageSpy';
import { appendRequestParams, fetchJSON, postForm } from '@/utils/request'
import { HT_HOST } from "@/config"
import { isNotEmpty, prepareUrl } from '@/utils/commons'
import { loadPageSpy } from '@/pageSpy'
import { useStorage } from '@/hooks/useStorage'
const KEY_LOGIN_TOKEN = 'KEY_LOGIN_TOKEN'
const KEY_TRAVEL_AGENCY_ID = 'KEY_TRAVEL_AGENCY_ID'
const KEY_USER_ID = 'KEY_USER_ID'
const KEY_LOGIN_TOKEN = 'GH-STR:LOGIN_TOKEN'
const KEY_TRAVEL_AGENCY_ID = 'GH-INT:TRAVEL_AGENCY_ID'
const KEY_USER_ID = 'GH-INT:USER_ID'
const useAuthStore = create((set, get) => ({
@ -97,11 +97,14 @@ const useAuthStore = create((set, get) => ({
},
logout: () => {
window.sessionStorage.clearSession()
const { clearStorage } = useStorage()
clearStorage()
set(() => ({
loginUser: {
token: '',
timeout: true
}
},
loginStatus: 0
}))
},

@ -13,6 +13,7 @@ import 'dayjs/locale/zh-cn';
import { BUILD_VERSION, } from '@/config';
import useNoticeStore from '@/stores/Notice';
import useAuthStore from '@/stores/Auth'
import { useStorage } from '@/hooks/useStorage'
const { Header, Content, Footer } = Layout;
const { Title } = Typography;
@ -25,11 +26,12 @@ function App() {
const loginUser = useAuthStore((state) => state.loginUser)
const { loginToken } = useStorage()
const noticeUnRead = useNoticeStore((state) => state.noticeUnRead);
const href = useHref();
const loginToken = loginUser.token;
const navigate = useNavigate();
const location = useLocation();
const navigate = useNavigate()
const location = useLocation()
useEffect(() => {
if (href !== '/login' && isEmpty(loginToken)) {
@ -151,7 +153,7 @@ function App() {
{ label: <Link to='/account/change-password'>{t('ChangePassword')}</Link>, key: '0' },
{ label: <Link to='/account/profile'>{t('Profile')}</Link>, key: '1' },
{ type: 'divider' },
{ label: <Link to='/login?out'>{t('Logout')}</Link>, key: '3' },
{ label: <Link to='/logout'>{t('Logout')}</Link>, key: '3' },
],
{ type: 'divider' },
{ label: <>v{BUILD_VERSION}</>, key: 'BUILD_VERSION' },

@ -1,28 +1,20 @@
import { useNavigate, useLocation } from 'react-router-dom';
import { useEffect } from 'react';
import { Button, Checkbox, Form, Input, Row, App } from 'antd';
import { useTranslation } from 'react-i18next';
import { useNavigate, useLocation } from 'react-router-dom'
import { useEffect } from 'react'
import { Button, Checkbox, Form, Input, Row, App } from 'antd'
import { useTranslation } from 'react-i18next'
import useAuthStore from '@/stores/Auth'
import useNoticeStore from '@/stores/Notice';
import useNoticeStore from '@/stores/Notice'
function Login() {
const [validateUserPassword, loginStatus, logout] =
const [validateUserPassword, loginStatus] =
useAuthStore((state) => [state.validateUserPassword, state.loginStatus])
const getBulletinUnReadCount = useNoticeStore((state) => state.getBulletinUnReadCount)
const { t, i18n } = useTranslation()
const { notification } = App.useApp();
const { notification } = App.useApp()
const navigate = useNavigate()
const location = useLocation()
const [form] = Form.useForm()
useEffect (() => {
if (location.search === '?out') {
logout();
navigate('/login')
}
}, [])
useEffect (() => {
if (loginStatus === 302) {
navigate('/reservation/newest')

@ -0,0 +1,31 @@
import { Flex, Result, Spin } from 'antd'
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import useAuthStore from '@/stores/Auth'
function Logout() {
const navigate = useNavigate()
const logout = useAuthStore(state => state.logout)
useEffect(() => {
logout()
navigate('/login')
}, [])
return (
<Flex justify='center' align='center' gap='middle' vertical>
<Result
status='success'
title='退出成功'
subTitle='正在跳转登陆页面'
extra={[
<Spin key='small-span' size='small' />
]}
/>
</Flex>
)
}
export default Logout
Loading…
Cancel
Save