createStorage.ts
3.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
export type queryProps = Record<string, {
totalCount?: number,
result: string[],
}>;
export type datasProps = Record<string, {
id: string,
[key: string]: any;
}>;
export interface storaProps {
type: string, // 当前类型
query: queryProps, // 搜索条件库
datas: datasProps, // 数据集合
}
export type storageProps = Record<string, storaProps>;
const storage: storageProps = {};
export interface actionProps {
type: string;
params?: any;
list?: any[];
strs?: string[];
totalCount?: number;
[key: string]: any;
}
export const FIND_STORAGE_TYPE = 'FIND_STORAGE_TYPE'; // 获取 find 类型数据
export const ADD_StORAGE_TYPE = 'ADD_STORAGE_LSIT'; // 添加数据集合到 stora.datas
export const QUERY_STORAGE_TYPE = 'QUERY_STORAGE_TYPE'; // 查询指定集合数据
export const MATCH_DATAS_TYPE = 'MATCH_DATAS_TYPE'; // 匹配传入的数据集合
export default (uuid: string | undefined) => {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
const key = uuid || getUUid();
if (!storage[key]) {
// 创建stora 库
storage[key] = {
type: key,
query: {},
datas: {},
};
}
const stora = storage[key];
// eslint-disable-next-line consistent-return
function reducer({ type, params, result, totalCount, vals }: actionProps) {
// eslint-disable-next-line default-case
switch (type) {
case FIND_STORAGE_TYPE:
// 根据查询条件匹配数据集合
// eslint-disable-next-line no-case-declarations
const query = stora.query[JSON.stringify(params)];
if (query) {
// 数据集合匹配成功
return {
// eslint-disable-next-line @typescript-eslint/no-shadow
result: query.result.map((key: string) => stora.datas[key]),
totalCount: query.totalCount,
}
}
return null;
case ADD_StORAGE_TYPE:
// 根据查询条件保存数据集合
// eslint-disable-next-line no-case-declarations
const paramKey = JSON.stringify(params);
if (!stora.query[paramKey]) {
stora.query[paramKey] = { result: [] };
}
stora.query[paramKey] = {
result: result?.map((item: any) => {
if (!stora.datas[item.id]) {
stora.datas[item.id] = item;
}
return item.id;
}) as string[],
totalCount: totalCount && Number(totalCount)
}
return true;
case QUERY_STORAGE_TYPE:
return vals?.map((id: string) => stora.datas[id]);
case MATCH_DATAS_TYPE:
return {
error: vals.filter((id: string) => !stora.datas[id]),
list: vals.filter((id: string) => stora.datas[id]).map((id: string) => stora.datas[id]),
}
}
}
return [stora, reducer]
}
/**
* 销毁指定stora 库
*/
export const destroyStora = (key: string) => {
delete storage[key];
}
/**
* 检测某个stora 库是否存
*/
export const isStorage = (key: string) => {
return !!storage[key];
}
let uuid_index = 0;
/**
* 生成对于 storage 不重复 uuid
*/
export const getUUid = () => {
// eslint-disable-next-line no-plusplus
return `uuid_${ uuid_index++ }`;
}