Skip to content

Commit

Permalink
refactor(utils): ♻️ add sessionStorage function
Browse files Browse the repository at this point in the history
  • Loading branch information
jsxiaosi committed Oct 27, 2022
1 parent 1b3e039 commit 8eadfcf
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 36 deletions.
2 changes: 0 additions & 2 deletions public/serverConfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
"hideTabs": false,
"labelPersistent": true,
"StorageConfig":{
"type": "localStorage",
"prefix": "xiaosiAdmin",
"expire": 0,
"isEncrypt": false
}
Expand Down
2 changes: 1 addition & 1 deletion src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export async function getServerConfig(app: App): Promise<AppConfig> {
throw `\npublic文件夹下无法查找到serverConfig配置文件\nUnable to find serverconfig configuration file under public folder`;
}
}
setStorageConfig(config.StorageConfig);
setStorageConfig({ ...config.StorageConfig, prefix: config.title });
app.config.globalProperties.$config = getConfig();
return config;
}
2 changes: 1 addition & 1 deletion src/store/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { RouteRecordName, _RouteLocationBase } from 'vue-router';
import type { StorageConfig } from '#/global';
import type { AppRouteRecordRaw } from '#/route';
import type { StorageConfig } from '@/utils/storage/types';

export interface AppState {
appConfigMode: AppConfig;
Expand Down
79 changes: 54 additions & 25 deletions src/utils/storage.ts → src/utils/storage/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import CryptoJS from 'crypto-js';
import type { StorageConfig } from '#/global';

type StorageValue<T> = T | null | undefined;
import type { StorageConfig, StorageType, StorageValue } from './types';

// 十六位十六进制数作为密钥
const SECRET_KEY = CryptoJS.enc.Utf8.parse('3333e6e143439161');
Expand All @@ -10,7 +8,6 @@ const SECRET_IV = CryptoJS.enc.Utf8.parse('e3bbe7e3ba84431a');

// 类型 window.localStorage,window.sessionStorage,
let config: StorageConfig = {
type: 'localStorage', // 本地存储类型 sessionStorage
prefix: 'xiaosiAdmin', // 名称前缀 建议:项目名 + 项目版本
expire: 0, //过期时间 单位:秒
isEncrypt: false, // 默认加密 为了调试方便, 开发过程中可以不加密
Expand All @@ -27,7 +24,12 @@ export const isSupportStorage = () => {
};

// 设置 setStorage
export const setStorage = <T>(key: string, value: StorageValue<T>, expire = 0) => {
export const setStorage = <T>(
key: string,
value: StorageValue<T>,
expire = 0,
type: StorageType = 'localStorage',
) => {
if (value === null || value === undefined) {
value = null;
}
Expand All @@ -43,24 +45,21 @@ export const setStorage = <T>(key: string, value: StorageValue<T>, expire = 0) =

const encryptString = config.isEncrypt ? encrypt(JSON.stringify(data)) : JSON.stringify(data);

window[config.type].setItem(autoAddPrefix(key), encryptString);
window[type].setItem(autoAddPrefix(key), encryptString);
};

// 获取 getStorage
export const getStorage = <T>(key: string): StorageValue<T> => {
export const getStorage = <T>(key: string, type: StorageType = 'localStorage'): StorageValue<T> => {
key = autoAddPrefix(key);
// key 不存在判断
if (
!window[config.type].getItem(key) ||
JSON.stringify(window[config.type].getItem(key)) === 'null'
) {
if (!window[type].getItem(key) || JSON.stringify(window[type].getItem(key)) === 'null') {
return null;
}

// 优化 持续使用中续期
const storage = config.isEncrypt
? JSON.parse(decrypt(window[config.type].getItem(key) || ''))
: JSON.parse(window[config.type].getItem(key) || '');
? JSON.parse(decrypt(window[type].getItem(key) || ''))
: JSON.parse(window[type].getItem(key) || '');

const nowTime = Date.now();

Expand Down Expand Up @@ -95,38 +94,38 @@ export const getStorageKeys = (): (string | null)[] => {
};

// 根据索引获取key
export const getStorageForIndex = (index: number) => {
return window[config.type].key(index);
export const getStorageForIndex = (index: number, type: StorageType = 'localStorage') => {
return window[type].key(index);
};

// 获取localStorage长度
export const getStorageLength = () => {
return window[config.type].length;
export const getStorageLength = (type: StorageType = 'localStorage') => {
return window[type].length;
};

// 获取全部 getAllStorage
export const getStorageAll = () => {
const len = window[config.type].length; // 获取长度
export const getStorageAll = (type: StorageType = 'localStorage') => {
const len = window[type].length; // 获取长度
const arr = []; // 定义数据集
for (let i = 0; i < len; i++) {
// 获取key 索引从0开始
const getKey = window[config.type].key(i) || '';
const getKey = window[type].key(i) || '';
// 获取key对应的值
const getVal = window[config.type].getItem(getKey);
const getVal = window[type].getItem(getKey);
// 放进数组
arr[i] = { key: getKey, val: getVal };
}
return arr;
};

// 删除 removeStorage
export const removeStorage = (key: string) => {
window[config.type].removeItem(autoAddPrefix(key));
export const removeStorage = (key: string, type: StorageType = 'localStorage') => {
window[type].removeItem(autoAddPrefix(key));
};

// 清空 clearStorage
export const clearStorage = () => {
window[config.type].clear();
export const clearStorage = (type: StorageType = 'localStorage') => {
window[type].clear();
};

// 名称前自动添加前缀
Expand All @@ -141,6 +140,36 @@ const autoRemovePrefix = (key: string) => {
return key.substr(len);
};

/** SessionStorage */

export const setSessionStorage = <T>(key: string, value: StorageValue<T>, expire = 0) => {
return setStorage<T>(key, value, expire, 'sessionStorage');
};

export const getSessionStorage = <T>(key: string): StorageValue<T> => {
return getStorage<T>(key, 'sessionStorage');
};

export const getSessionStorageForIndex = (index: number) => {
return getStorageForIndex(index, 'sessionStorage');
};

export const getSessionStorageLength = () => {
return getStorageLength('sessionStorage');
};

export const getSessionStorageAll = () => {
return getStorageAll('sessionStorage');
};

export const removeSessionStorage = (key: string) => {
return removeStorage(key, 'sessionStorage');
};

export const clearSessionStorage = () => {
return clearStorage('sessionStorage');
};

/**
* 加密方法
* @param data
Expand Down
9 changes: 9 additions & 0 deletions src/utils/storage/types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export type StorageValue<T> = T | null | undefined;

export type StorageType = 'localStorage' | 'sessionStorage';

export interface StorageConfig {
prefix: string;
expire: number;
isEncrypt: boolean;
}
7 changes: 0 additions & 7 deletions types/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,3 @@ declare module '*.vue' {
const Component: DefineComponent<{}, {}, any>;
export default Component;
}

export interface StorageConfig {
type: 'localStorage' | 'sessionStorage';
prefix: string;
expire: number;
isEncrypt: boolean;
}

0 comments on commit 8eadfcf

Please sign in to comment.