Skip to main content
Version: 2.x

使用 DBUtil

一、 DBUtil 是什么

DBUtil 是一个自动识别运行环境并选取合适存储方式, 并对外提供一致 api 的存储工具库。

  • 浏览器环境: 使用 IndexedDB 存储
  • Electron 环境: 使用文件存储
  • 提供 Adaptor:自定义存储方式(例如存储到后台数据库)

二、 使用

1. 初始化

import { DBUtil } from '@gza/quantex-utils';
// 初始化db,
DBUtil.initDB(['custom_ag_table']); // return promise

2. 使用(不按用户存储)

import { DBUtil } from '@gza/quantex-utils';

const dbUtil = DBUtil.wrapperTableName('custom_ag_table');

dbUtil.insertData({ id: 1 }); // return promise
dbUtil.getDataByKey(1); // return promise
dbUtil.updateData({ id: 1 }); // return promise
dbUtil.deleteData(1); // return promise
dbUtil.queryData(); // return promise
dbUtil.clearStore();

3. 使用(按用户存储)

这种方式仅适用于 DBUtil 提供的默认存储方式,如果是自定义 Adaptor,一般都是要按照用户存储的

import { DBUtil } from '@gza/quantex-utils';

// 初始化时,传入用户编码
const userCode = userLocalStore.getItem('userInfo').code;
const dbUtil = DBUtil.wrapperTableName('workbench_table', userCode);

dbUtil.insertData({ id: 1 }); // return promise
dbUtil.getDataByKey(1); // return promise
dbUtil.updateData({ id: 1 }); // return promise
dbUtil.deleteData(1); // return promise
dbUtil.queryData(); // return promise
dbUtil.clearStore();

4. 使用自定义 Adaptor

如果我们要将数据保存到数据库,则可以使用 DBUtil.Adaptor(tableNames, adaptor) 模式,例如下面示例代码,将表格模板数据、工作台模板数据保存到后端数据库,只需要实现相应的方法(API)即可。可以多次调用 DBUtil.Adaptor 方法,tableName 一样会覆盖

// 修改app/layouts/index.ts(如果没有则新增),在layouts.main.afterGlobalInit方法实现如下逻辑

import defaultLayouts from '@/containers/defaultLayouts';
import { cloneDeep, memoize } from 'lodash';
import { DBUtil, API } from '@gza/quantex-utils';
import appWindow from 'common/appWindow';

// 这里需要先深拷贝一份配置
const layouts = cloneDeep(defaultLayouts);

layouts.main.afterGlobalInit = () => {
const api = new API('auth');

// 引入缓存机制,减少不必要的查询
// 首次【查询】数据后缓存结果
// 【保存/更新】数据后更新缓存
// 【删除】数据后删除缓存
const cacheMap = new Map();
const adaptor: Parameters<typeof DBUtil.setAdaptor>[1] = {
initDB: tableName => {
// initDB这个方法如果没有用到可以不提供(实现)
},
wrapperTableName: tableName => {
let tplName: string;
// 这里只是为了优化代码,实际上代码怎么写都无所谓
if (tableName === 'custom_ag_table') {
tplName = 'table_tpls';
} else {
tplName = 'workbenchs';
}
const getCacheKey = (id: string) => {
const userCode = appWindow.sessionStore.getItem('userCode');
return tableName + '/' + userCode + '/' + id;
};
return {
/**
* 根据id查询数据,数据结构一般为
* {
* id:string, 模板Id,由框架提供
* config:object, 模板配置,一般是一个json结构,后端直接用blob类型文本存储即可
* userCode:string,用户编码,这个框架没有提供,后端需要获取当前用户并保存,
* }
*/
getDataByKey: async id => {
if (!id) {
return null;
}
const cacheKey = getCacheKey(id);
if (cacheMap.has(cacheKey)) {
// 深拷贝一份以防被修改
return cloneDeep(cacheMap.get(cacheKey));
}
// 调用接口查询数据
const res = await api.get('/api/v1/{tplName}/{id}', { id, tplName });
if (res.code === 200) {
// 保存缓存结果
cacheMap.set(cacheKey, res.data);
return res.data;
} else {
return null;
}
},
/**
* 保存数据,数据结构为
* {
* id: string,
* config: object
* }
*/
insertData: async params => {
params.tplName = tplName;
const res = await api.post('/api/v1/{tplName}', params, { loading: false });
if (res.code !== 200) {
return Promise.reject(res);
}

// 更新缓存
const cacheKey = getCacheKey(params.id);
cacheMap.set(cacheKey, cloneDeep(params));

return (res as any).data.id;
},
/**
* 更新数据,数据结构为
* {
* id: string,
* config: object
* }
*/
updateData: async params => {
params.tplName = tplName;
const res = await api.put('/api/v1/{tplName}/{id}', params, { loading: false });
if (res.code !== 200) {
return Promise.reject(res);
}

// 更新缓存
const cacheKey = getCacheKey(params.id);
cacheMap.set(cacheKey, cloneDeep(params));
},
/**
* 删除数据
*/
deleteData: async id => {
const res = await api.delete('/api/v1/{tplName}/{id}', { id, tplName }, { loading: false });
if (res.code != 200) {
return Promise.reject(res);
}

// 删除缓存
const cacheKey = getCacheKey(id);
cacheMap.delete(cacheKey);
},
/**
* 查询用户所有模板数据,数据结构为
* [
* {
* id: string,
* config: object,
* userCode:string
* }
* ]
*/
queryData: async () => {
// custom_ag_table没用到这个函数
const res = await api.get('/api/v1/{tplName}/list', { tplName });
if (res.code == 200) {
return (res as any).data.list;
}
return [];
}
};
}
};
adaptor.wrapperTableName = memoize(adaptor.wrapperTableName);
// 这里将表格模板和工作台模板都保存到数据库,你也可以只处理一个模板
DBUtil.setAdaptor(['custom_ag_table', 'workbench_table'], adaptor);
};

layouts.main.sendMetrics = params => {
let api = new API('auth');
return api.post('/api/v1/client_metrics', params, { loading: false });
};

export default layouts;