携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第18天,点击查看活动详情
前言
前端的工具库,常用的也都比较多,一些数据转换、格式化、存储等,也都比较杂,我们试着进行一个大的归类
- cache 本地存储相关
缓存类型 'local'(默认) / cookie / session
- 前端数据库 indexDB 公共方法
页面之间的传参使用,使用db.js进行临时存储
cache
前端缓存:封装了 sessionStorage、localStorage、Cookie 的读写方法。
注意:type 不传默认为“local”,存储对数据使用了 JSON.stringify 处理,引用类型无需再次转换。
API
type CacheType = 'session' | 'local' | 'cookie';
cache.getCache(key: string, type?: CacheType): any;
cache.setCache(key: string, value: any, type?: CacheType): any;
cache.getUserCache(key: string, type?: CacheType): any;
cache.setUserCache(key: string, value: any, type?: CacheType): any;
参数说明
参数 | 说明 | 类型 |
---|---|---|
key | 唯一索引 | string |
value | 存储数据 | any |
type | 存储类型 | session / local / cookie |
业务应用
import { cache } from '@basic-utils';
cache.setCache('cache', data, 'session');
const data = cache.getCache('cache', 'session'),
源代码
import Cookie from 'js-cookie';
/**
* 获取缓存数据
* @param {string} key
* @param {string} type: 缓存类型 'local'(默认) / cookie / session;
*/
function getCache(key, type = 'local') {
let data;
switch (type) {
case 'cookie':
data = Cookie.get(key);
break;
case 'session':
// eslint-disable-next-line no-case-declarations
let strS = sessionStorage.getItem(key);
try {
data = JSON.parse(strS);
} catch (e) {
data = strS;
}
break;
default:
// eslint-disable-next-line no-case-declarations
let strL = localStorage.getItem(key);
try {
data = JSON.parse(strL);
} catch (e) {
data = strL;
}
break;
}
return data;
}
/**
* 获取缓存数据
* @param {string} key
* @param {any} value
* @param {string} type: 缓存类型 'local'(默认) / cookie / session;
*/
function setCache(key, value, type = 'local') {
switch (type) {
case 'cookie':
Cookie.set(key, value, { expires: 7 });
break;
case 'session':
sessionStorage.setItem(key, JSON.stringify(value));
break;
default:
localStorage.setItem(key, JSON.stringify(value));
break;
}
}
/**
* 获取用户缓存
* @param {*} key
* @param {*} type
*/
function getUserCache(key, type = 'local') {
const id = getCache('userId', 'session');
if (!id) {
console.error('无法获取用户信息!');
return;
}
return getCache(`${id}-${key}`, type);
}
/**
* 设置用户缓存
* @param {*} key
* @param {*} value
* @param {*} type
*/
function setUserCache(key, value, type = 'local') {
const id = getCache('userId', 'session');
if (!id) {
console.error('无法获取用户信息!');
return;
}
return setCache(`${id}-${key}`, value, type);
}
function removeCookies(key) {
key && Cookie.remove(key);
}
export default {
getCache,
setCache,
getUserCache,
setUserCache,
removeCookies
};
db
前端数据库 indexDB 公共方法,页面之间的传参使用,使用db.js进行临时存储
// 引用方式:
import { EDU_DB } from "@basic-utils";
//存储
const sendParams = {
'params1':'参数值1'
}
EDU_DB.put('key_01', sendParams )
//读取
const res = await EDU_DB.get({ id: 'key_01' });
console.info(res.params1)
参数说明
参数 | 说明 | 类型 |
---|---|---|
schemaName | 非必填--默认表名(EDU_DB_T) | string |
id | 主键 | string |
EDU_DB 说明: EDU_DB.put和get方式,实现机制是在IndexDB进行存储,进行异步操作,适用于页面大数据量传参
get方式获取返回值,返回的是promise对象,需要使用then或者await进行接收,但vue3中script setup方式,支持await目前还处于实验阶段(使用会报错)
vue3 关于script setup 使用await 官方说明 vuejs.org/api/sfc-scr…
业务应用:
方式一:
import { EDU_DB } from "@basic-utils"
EDU_DB.get({ id: 'key_01' }).then((res)=>{
// res参数值
});
方式二:
import { EDU_DB } from "@basic-utils"
onMounted(async() => {
// 页面加载完成后
cont params = await EDU_DB.get({ id: 'key_01' })
})
源代码
import db from "db.js";
import cache from '../cache';
const schema = {
key: { keyPath: 'id', autoIncrement: true },
indexes: {
id: { unique: true },
time: { unique: false },
expireTime: { unique: false },
userId: { unique: false },
},
};
class DBInstance {
constructor(schemaName) {
this.EDU_DB_SERVER = null;
this.schemaName = schemaName || 'EDU_DB';
this.version = 1;
this._init();
}
async _init() {
this.EDU_DB_SERVER = await db.open({
server: this.schemaName, version: this.version, schema: {
[this.schemaName + '_T']: schema
}
});
}
get isClosed() {
return this.EDU_DB_SERVER ? this.EDU_DB_SERVER.isClosed() : true;
}
async get({ schemaName = "EDU_DB_T", id }) {
if (!id) {
return Promise.reject({ message: "IndexDB主键id不存在" });
}
if (this.isClosed) {
await this._init();
}
this.removeExpireData(schemaName);
return this.EDU_DB_SERVER[schemaName].get(id);
}
async put(id, data) {
if (!id) {
return Promise.reject({ message: "主键id不存在" });
}
data.id = id;
const { schemaName = "EDU_DB_T", expireTime = Date.now() + 7 * 24 * 60 * 60 * 1000, ...params } = data;
params.userId = cache.getCache('userId', 'session');
params.time = Date.now();
if (this.isClosed) {
await this._init();
}
this.removeExpireData(schemaName);
return this.EDU_DB_SERVER[schemaName].update({ expireTime, ...params });
}
async remove(ids, schemaName = "EDU_DB_T") {
if (this.isClosed) {
await this._init();
}
return Promise.all(ids.map(id => this.EDU_DB_SERVER[schemaName].remove(id)));
}
async removeExpireData(schemaName) {
if (this.isClosed) {
await this._init();
}
const result = await this.EDU_DB_SERVER[schemaName]
.query()
.filter(item => item.expireTime < Date.now())
.execute();
return this.remove(schemaName, result.map(v => v.id));
}
async clear(schemaName) {
if (this.isClosed) {
await this._init();
}
return this.EDU_DB_SERVER[schemaName].clear();
}
async count(schemaName) {
if (this.isClosed) {
await this._init();
}
return this.EDU_DB_SERVER[schemaName].count();
}
async update(schemaName, ...args) {
if (this.isClosed) {
await this._init();
}
this.removeExpireData(schemaName);
return this.EDU_DB_SERVER[schemaName].update(...args);
}
async query(schemaName) {
if (this.isClosed) {
await this._init();
}
return this.EDU_DB_SERVER[schemaName]
.query()
.filter(v => v.userId === cache.getCache('userId', 'session'))
.execute();
}
}
export default new DBInstance();
下章我们来聊聊,消息通信相关的函数封装....
加油,老铁...