-
Notifications
You must be signed in to change notification settings - Fork 1
/
getValueWithRedisAndSql.ts
99 lines (84 loc) · 2.58 KB
/
getValueWithRedisAndSql.ts
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
import { logEnvId } from '../src/env';
import {
fe,
// useContext,
run,
// useMemo,
// setContext,
createContext,
mockFn,
setMock,
} from '../src/index';
setMock(true);
const RedisContext = createContext<{ search: any; save: any } | null>(null);
const OrmContext = createContext<{ search: any } | null>(null);
const getRedisConfig = async () => 'redis config';
const createRedis = (config: string) => ({
search: () => 'data',
save: () => {},
});
const redisSearch = (redis: any, ...args: any[]): string | null => 'data';
mockFn(redisSearch, () => null);
const getOrmConfig = async () => 'redis config';
const createOrm = (config: string) => ({
search: () => 'orm data',
save: () => {},
});
const ormSearch = (redis: any, ...args: any[]) => 'orm data';
const isEmpty = (v: any) => false;
const main = fe(
({ call, trigger, useContext, useMemo, setContext }) => async (
...props: any[]
) => {
logEnvId();
const redisConfig = await call(getRedisConfig);
logEnvId();
const redis = await useMemo('redis', () => call(createRedis, redisConfig), [
redisConfig,
]);
logEnvId();
setContext(RedisContext, redis);
const ormConfig = await call(getOrmConfig);
logEnvId();
const orm = await useMemo('orm', () => call(createOrm, ormConfig), [
ormConfig,
]);
logEnvId();
setContext(OrmContext, orm);
const resultFromCache = await trigger(getFromCache, ...props);
logEnvId();
if (!!resultFromCache) return resultFromCache;
const resultFromSql = await trigger(getFromSql, ...props);
if (!!resultFromSql) {
if (!isEmpty(resultFromSql))
await trigger(saveCache, resultFromSql, ...props);
logEnvId();
return resultFromSql;
}
throw new Error('查找不到');
},
);
const getKey = (...args: any[]) => 'key';
const getFromCache = fe(({ call, useContext }) => (...props: any[]) => {
const redisKey = getKey(...props);
logEnvId();
const redis = useContext(RedisContext);
console.log(
'%c [ redis ]',
'font-size:13px; background:pink; color:#bf2c9f;',
redis,
);
return call(redisSearch, redis, redisKey);
});
const createFilter = async (...args: any[]) => 'filter';
const getFromSql = fe(({ call, useContext }) => async (...props) => {
const filter = await call(createFilter, ...props);
const orm = useContext(OrmContext);
return call(ormSearch, orm, filter);
});
const saveCache = fe(({ call, useContext }) => (...props) => {
const key = getKey(...props);
const redis = useContext(RedisContext);
return call(() => redis?.save(key));
});
run(main).then(console.log);