Skip to content

Commit

Permalink
refactor(projects): new storage system [新的本地数据存储系统]
Browse files Browse the repository at this point in the history
  • Loading branch information
honghuangdc committed Nov 16, 2022
1 parent 7a58035 commit 9719159
Show file tree
Hide file tree
Showing 23 changed files with 165 additions and 190 deletions.
5 changes: 2 additions & 3 deletions src/components/common/AppLoading.vue
Expand Up @@ -16,9 +16,8 @@
</template>

<script setup lang="ts">
import { EnumStorageKey } from '@/enum';
import { useAppInfo } from '@/composables';
import { getLocal } from '@/utils';
import { localStg } from '@/utils';
const { title } = useAppInfo();
Expand All @@ -31,7 +30,7 @@ const lodingClasses = [
function addThemeColorCssVars() {
const defaultColor = '#1890ff';
const themeColor = getLocal(EnumStorageKey['theme-color']) || defaultColor;
const themeColor = localStg.get('themeColor') || defaultColor;
const cssVars = `--primary-color: ${themeColor}`;
document.documentElement.style.cssText = cssVars;
}
Expand Down
16 changes: 0 additions & 16 deletions src/enum/common.ts
Expand Up @@ -5,22 +5,6 @@ export enum EnumContentType {
formData = 'multipart/form-data'
}

/** 缓存的key */
export enum EnumStorageKey {
/** 主题颜色 */
'theme-color' = '__THEME_COLOR__',
/** 用户token */
'token' = '__TOKEN__',
/** 用户刷新token */
'refresh-token' = '__REFRESH_TOKEN__',
/** 用户信息 */
'user-info' = '__USER_INFO__',
/** 主题配置 */
'theme-settings' = '__THEME_SETTINGS__',
/** 多页签路由信息 */
'multi-tab-routes' = '__MULTI_TAB_ROUTES__'
}

/** 数据类型 */
export enum EnumDataType {
number = '[object Number]',
Expand Down
4 changes: 2 additions & 2 deletions src/router/guard/dynamic.ts
@@ -1,7 +1,7 @@
import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router';
import { routeName } from '@/router';
import { useRouteStore } from '@/store';
import { getToken } from '@/utils';
import { localStg } from '@/utils';

/**
* 动态路由
Expand All @@ -12,7 +12,7 @@ export async function createDynamicRouteGuard(
next: NavigationGuardNext
) {
const route = useRouteStore();
const isLogin = Boolean(getToken());
const isLogin = Boolean(localStg.get('token'));

// 初始化权限路由
if (!route.isInitAuthRoute) {
Expand Down
4 changes: 2 additions & 2 deletions src/router/guard/permission.ts
@@ -1,7 +1,7 @@
import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router';
import { routeName } from '@/router';
import { useAuthStore } from '@/store';
import { exeStrategyActions, getToken } from '@/utils';
import { exeStrategyActions, localStg } from '@/utils';
import { createDynamicRouteGuard } from './dynamic';

/** 处理路由页面的权限 */
Expand All @@ -22,7 +22,7 @@ export async function createPermissionGuard(
}

const auth = useAuthStore();
const isLogin = Boolean(getToken());
const isLogin = Boolean(localStg.get('token'));
const permissions = to.meta.permissions || [];
const needLogin = Boolean(to.meta?.requiresAuth) || Boolean(permissions.length);
const hasPermission = !permissions.length || permissions.includes(auth.userInfo.userRole);
Expand Down
9 changes: 5 additions & 4 deletions src/service/request/helpers.ts
@@ -1,6 +1,6 @@
import type { AxiosRequestConfig } from 'axios';
import { useAuthStore } from '@/store';
import { getRefreshToken, setRefreshToken, setToken } from '@/utils';
import { localStg } from '@/utils';
import { fetchUpdateToken } from '../api';

/**
Expand All @@ -9,11 +9,12 @@ import { fetchUpdateToken } from '../api';
*/
export async function handleRefreshToken(axiosConfig: AxiosRequestConfig) {
const { resetAuthStore } = useAuthStore();
const refreshToken = getRefreshToken();
const refreshToken = localStg.get('refreshToken') || '';
const { data } = await fetchUpdateToken(refreshToken);
if (data) {
setToken(data.token);
setRefreshToken(data.refreshToken);
localStg.set('token', data.token);
localStg.set('refreshToken', data.refreshToken);

const config = { ...axiosConfig };
if (config.headers) {
config.headers.Authorization = data.token;
Expand Down
4 changes: 2 additions & 2 deletions src/service/request/instance.ts
Expand Up @@ -2,7 +2,7 @@ import axios from 'axios';
import type { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios';
import { REFRESH_TOKEN_CODE } from '@/config';
import {
getToken,
localStg,
handleAxiosError,
handleBackendError,
handleResponseError,
Expand Down Expand Up @@ -49,7 +49,7 @@ export default class CustomAxiosInstance {
const contentType = handleConfig.headers['Content-Type'] as string;
handleConfig.data = await transformRequestData(handleConfig.data, contentType);
// 设置token
handleConfig.headers.Authorization = getToken();
handleConfig.headers.Authorization = localStg.get('token') || '';
}
return handleConfig;
},
Expand Down
25 changes: 25 additions & 0 deletions src/store/modules/auth/helpers.ts
@@ -0,0 +1,25 @@
import { localStg } from '@/utils';

/** 获取token */
export function getToken() {
return localStg.get('token') || '';
}

/** 获取用户信息 */
export function getUserInfo() {
const emptyInfo: Auth.UserInfo = {
userId: '',
userName: '',
userRole: 'user'
};
const userInfo: Auth.UserInfo = localStg.get('userInfo') || emptyInfo;

return userInfo;
}

/** 去除用户相关缓存 */
export function clearAuthStorage() {
localStg.remove('token');
localStg.remove('refreshToken');
localStg.remove('userInfo');
}
9 changes: 5 additions & 4 deletions src/store/modules/auth/index.ts
Expand Up @@ -3,9 +3,10 @@ import { defineStore } from 'pinia';
import { router } from '@/router';
import { fetchLogin, fetchUserInfo } from '@/service';
import { useRouterPush } from '@/composables';
import { clearAuthStorage, getToken, getUserInfo, setRefreshToken, setToken, setUserInfo } from '@/utils';
import { localStg } from '@/utils';
import { useTabStore } from '../tab';
import { useRouteStore } from '../route';
import { getToken, getUserInfo, clearAuthStorage } from './helpers';

interface AuthState {
/** 用户信息 */
Expand Down Expand Up @@ -81,14 +82,14 @@ export const useAuthStore = defineStore('auth-store', {

// 先把token存储到缓存中(后面接口的请求头需要token)
const { token, refreshToken } = backendToken;
setToken(token);
setRefreshToken(refreshToken);
localStg.set('token', token);
localStg.set('refreshToken', refreshToken);

// 获取用户信息
const { data } = await fetchUserInfo();
if (data) {
// 成功后把用户信息存储到缓存中
setUserInfo(data);
localStg.set('userInfo', data);

// 更新状态
this.userInfo = data;
Expand Down
12 changes: 7 additions & 5 deletions src/store/modules/route/index.ts
Expand Up @@ -2,10 +2,10 @@ import { defineStore } from 'pinia';
import { ROOT_ROUTE, constantRoutes, router, routes as staticRoutes } from '@/router';
import { fetchUserRoutes } from '@/service';
import {
localStg,
filterAuthRoutesByUserPermission,
getCacheRoutes,
getConstantRouteNames,
getUserInfo,
transformAuthRouteToVueRoutes,
transformAuthRouteToVueRoute,
transformAuthRouteToMenu,
Expand Down Expand Up @@ -106,7 +106,12 @@ export const useRouteStore = defineStore('route-store', {
},
/** 初始化动态路由 */
async initDynamicRoute() {
const { userId } = getUserInfo();
const { userId } = localStg.get('userInfo') || {};

if (!userId) {
throw new Error('userId 不能为空!');
}

const { data } = await fetchUserRoutes(userId);
if (data) {
this.routeHomeName = data.home;
Expand All @@ -123,9 +128,6 @@ export const useRouteStore = defineStore('route-store', {
/** 初始化权限路由 */
async initAuthRoute() {
const { initHomeTab } = useTabStore();
const { userId } = getUserInfo();

if (!userId) return;

const isDynamicRoute = this.authRouteMode === 'dynamic';
if (isDynamicRoute) {
Expand Down
12 changes: 3 additions & 9 deletions src/store/modules/tab/helpers.ts
@@ -1,6 +1,5 @@
import type { RouteLocationNormalizedLoaded, RouteRecordNormalized } from 'vue-router';
import { EnumStorageKey } from '@/enum';
import { getLocal, setLocal } from '@/utils';
import { localStg } from '@/utils';

/**
* 根据vue路由获取tab路由
Expand Down Expand Up @@ -58,15 +57,10 @@ function hasFullPath(
return Boolean((route as RouteLocationNormalizedLoaded).fullPath);
}

/** 缓存多页签数据 */
export function setTabRoutes(data: App.GlobalTabRoute[]) {
setLocal(EnumStorageKey['multi-tab-routes'], data);
}

/** 获取缓存的多页签数据 */
export function getTabRoutes() {
const routes: App.GlobalTabRoute[] = [];
const data = getLocal<App.GlobalTabRoute[]>(EnumStorageKey['multi-tab-routes']);
const data = localStg.get('multiTabRoutes');
if (data) {
const defaultTabRoutes = data.map(item => ({
...item,
Expand All @@ -82,5 +76,5 @@ export function getTabRoutes() {

/** 清空多页签数据 */
export function clearTabRoutes() {
setTabRoutes([]);
localStg.set('multiTabRoutes', []);
}
6 changes: 3 additions & 3 deletions src/store/modules/tab/index.ts
@@ -1,15 +1,15 @@
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
import { defineStore } from 'pinia';
import { useRouterPush } from '@/composables';
import { localStg } from '@/utils';
import { useThemeStore } from '../theme';
import {
clearTabRoutes,
getIndexInTabRoutes,
getIndexInTabRoutesByRouteName,
getTabRouteByVueRoute,
getTabRoutes,
isInTabRoutes,
setTabRoutes
isInTabRoutes
} from './helpers';

interface TabState {
Expand Down Expand Up @@ -52,7 +52,7 @@ export const useTabStore = defineStore('tab-store', {
},
/** 缓存页签路由数据 */
cacheTabRoutes() {
setTabRoutes(this.tabs);
localStg.set('multiTabRoutes', this.tabs);
},
/**
* 设置当前路由对应的页签为激活状态
Expand Down
22 changes: 3 additions & 19 deletions src/store/modules/theme/helpers.ts
@@ -1,19 +1,18 @@
import type { GlobalThemeOverrides } from 'naive-ui';
import { cloneDeep } from 'lodash-es';
import { themeSetting } from '@/settings';
import { EnumStorageKey } from '@/enum';
import { addColorAlpha, getColorPalette, getLocal, getThemeColor, removeLocal, setLocal } from '@/utils';
import { localStg, addColorAlpha, getColorPalette } from '@/utils';

/** 初始化主题配置 */
export function initThemeSettings() {
const isProd = import.meta.env.PROD;
// 生产环境才缓存主题配置,本地开发实时调整配置更改配置的json
const storageSettings = getThemeSettings();
const storageSettings = localStg.get('themeSettings');
if (isProd && storageSettings) {
return storageSettings;
}

const themeColor = getThemeColor() || themeSetting.themeColor;
const themeColor = localStg.get('themeColor') || themeSetting.themeColor;
const info = themeSetting.isCustomizeInfoColor ? themeSetting.otherColor.info : getColorPalette(themeColor, 7);
const otherColor = { ...themeSetting.otherColor, info };
const setting = cloneDeep({ ...themeSetting, themeColor, otherColor });
Expand Down Expand Up @@ -78,18 +77,3 @@ export function getNaiveThemeOverrides(colors: Record<ColorType, string>): Globa
}
};
}

/** 获取缓存中的主题配置 */
function getThemeSettings() {
return getLocal<Theme.Setting>(EnumStorageKey['theme-settings']);
}

/** 获取缓存中的主题配置 */
export function setThemeSettings(settings: Theme.Setting) {
return setLocal(EnumStorageKey['theme-settings'], settings);
}

/** 清除缓存配置 */
export function clearThemeSettings() {
removeLocal(EnumStorageKey['theme-settings']);
}
7 changes: 4 additions & 3 deletions src/store/modules/theme/index.ts
@@ -1,6 +1,7 @@
import { defineStore } from 'pinia';
import { darkTheme } from 'naive-ui';
import { clearThemeSettings, getNaiveThemeOverrides, initThemeSettings, setThemeSettings } from './helpers';
import { localStg } from '@/utils';
import { getNaiveThemeOverrides, initThemeSettings } from './helpers';

type ThemeState = Theme.Setting;

Expand All @@ -24,14 +25,14 @@ export const useThemeStore = defineStore('theme-store', {
actions: {
/** 重置theme状态 */
resetThemeStore() {
clearThemeSettings();
localStg.remove('themeSettings');
this.$reset();
},
/** 缓存主题配置 */
cacheThemeSettings() {
const isProd = import.meta.env.PROD;
if (isProd) {
setThemeSettings(this.$state);
localStg.set('themeSettings', this.$state);
}
},
/** 设置暗黑模式 */
Expand Down
4 changes: 2 additions & 2 deletions src/store/subscribe/theme.ts
Expand Up @@ -3,7 +3,7 @@ import { useOsTheme } from 'naive-ui';
import type { GlobalThemeOverrides } from 'naive-ui';
import { useElementSize } from '@vueuse/core';
import { kebabCase } from 'lodash-es';
import { setThemeColor } from '@/utils';
import { localStg } from '@/utils';
import { useThemeStore } from '../modules';

/** 订阅theme store */
Expand All @@ -17,7 +17,7 @@ export default function subscribeThemeStore() {
const stopThemeColor = watch(
() => theme.themeColor,
newValue => {
setThemeColor(newValue);
localStg.set('themeColor', newValue);
},
{ immediate: true }
);
Expand Down
22 changes: 22 additions & 0 deletions src/typings/storage.d.ts
@@ -0,0 +1,22 @@
declare namespace StorageInterface {
/** localStorage的存储数据的类型 */
interface Session {
demoKey: string;
}

/** localStorage的存储数据的类型 */
interface Local {
/** 主题颜色 */
themeColor: string;
/** 用户token */
token: string;
/** 用户刷新token */
refreshToken: string;
/** 用户信息 */
userInfo: Auth.UserInfo;
/** 主题配置 */
themeSettings: Theme.Setting;
/** 多页签路由信息 */
multiTabRoutes: App.GlobalTabRoute[];
}
}
1 change: 0 additions & 1 deletion src/utils/auth/index.ts

This file was deleted.

1 comment on commit 9719159

@vercel
Copy link

@vercel vercel bot commented on 9719159 Nov 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.