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() { export function useStorage() {
const setSession = (key, value) => { const getStorage = () => {
if (window.sessionStorage) { if (import.meta.env.DEV && window.localStorage) {
const sessionStorage = window.sessionStorage return window.localStorage
return sessionStorage.setItem(key, value) } else if (window.sessionStorage) {
return window.sessionStorage
} else { } 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) => { const camelCasedWords = (string) => {
if (typeof string !== 'string' || string.length === 0) { if (typeof string !== 'string' || string.length === 0) {
return string; return string;
} }
return string.split('_').map((word, index) => { return string.split('_').map((word, index) => {
if (index === 0) { if (index === 0) {
return ''
} else if (index === 1) {
return word.toLowerCase() return word.toLowerCase()
} else { } else {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
@ -24,27 +40,34 @@ export function useStorage() {
}).join('') }).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++) { if (typeAndKey.length === 2) {
const key = sessionStorage.key(i) const value = webStorage.getItem(key)
const value = sessionStorage.getItem(key) const propName = camelCasedWords(typeAndKey[1])
const propName = camelCasedWords(key) if (typeAndKey[0] === 'GH-INT') {
storageObject[propName] = value persistObject[propName] = parseInt(value, 10)
} else {
persistObject[propName] = value
}
}
}
} }
return { return {
...storageObject, ...persistObject,
setStorage: (key, value) => { 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 App from "@/views/App";
import Standlone from "@/views/Standlone"; import Standlone from "@/views/Standlone";
import Login from "@/views/Login"; import Login from "@/views/Login";
import Logout from "@/views/Logout";
import Index from "@/views/index"; import Index from "@/views/index";
import ErrorPage from "@/views/error-page"; import ErrorPage from "@/views/error-page";
import ReservationNewest from "@/views/reservation/Newest"; import ReservationNewest from "@/views/reservation/Newest";
@ -66,6 +67,7 @@ const router = createBrowserRouter([
element: <Standlone />, element: <Standlone />,
children: [ children: [
{ path: "/login", element: <Login /> }, { path: "/login", element: <Login /> },
{ path: "/logout", element: <Logout /> },
] ]
} }
]); ]);

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

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

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