@@ -45,46 +45,32 @@ import StaleWhileRevalidate from './assets/stale-while-revalidate.png'
4545import { request , KeqMiddleware } from " keq"
4646import { KeqCacheStrategy , KeqCacheParameters , CacheEntry } from " @keq-request/cache"
4747
48- const MyCacheFirstStrategy: KeqCacheStrategy = function (params : KeqCacheParameters ): KeqMiddleware {
49- const { storage, key } = params
50-
51- return async function (context , next ) {
52- const cache = await storage .get (key )
53-
54- if (cache ) {
55- context .res = cache .response
56- context .emitter .emit (' cache:hit' , { key , response: context .response , context }) // 不要忘记触发缓存命中事件
57- return
58- }
59-
60- context .emitter .emit (' cache:miss' , { key , context }) // 不要忘记触发缓存未命中事件
61-
62- // 发送请求
63- await next ()
64-
65- if (context .response ) {
66- // 检查是否应该可以缓存
67- if (params .exclude && (await params .exclude (context .response ))) {
68- return
69- }
70-
71- // 构建缓存
72- const entry = await CacheEntry .build ({
73- key: key ,
74- response: context .response ,
75- ttl: params .ttl ,
76- })
77-
78- await storage .set (entry )
79-
80- // 不要忘记触发缓存更新事件
81- context .emitter .emit (' cache:update' , {
82- key ,
83- oldResponse: undefined ,
84- newResponse: entry .response ,
85- context ,
86- })
87- }
48+ const MyCacheFirstStrategy: KeqCacheStrategy = async function (handler , context , next ) {
49+ // const { storage, key } = params
50+
51+ // return async function (context, next) {
52+ const [key,cache] = await handler .getCache (context )
53+
54+ if (cache ) {
55+ context .res = cache .response
56+ context .emitter .emit (' cache:hit' , { key , response: context .response , context }) // 不要忘记触发缓存命中事件
57+ return
58+ }
59+
60+ context .emitter .emit (' cache:miss' , { key , context }) // 不要忘记触发缓存未命中事件
61+
62+ // 发送请求
63+ await next ()
64+
65+ const [, entry] = await handler .setCache (context , key )
66+ if (entry ) {
67+ // 不要忘记触发缓存更新事件
68+ context .emitter .emit (' cache:update' , {
69+ key: entry .key ,
70+ oldResponse: cache ?.response ,
71+ newResponse: entry .response ,
72+ context ,
73+ })
8874 }
8975}
9076
@@ -109,13 +95,13 @@ import { KeqCacheStrategy, Strategies } from "@keq-request/cache"
10995
11096const isNetworkFast = true
11197
112- const MyStrategy: KeqCacheStrategy = function (params ) {
98+ const MyStrategy: KeqCacheStrategy = async function (handler , context , next ) {
11399 // 根据条件选择不同的策略
114100 if (isNetworkFast ) {
115- return Strategies .NETWORK_FIRST (params )
101+ return Strategies .NETWORK_FIRST (handler , context , next )
116102 } else {
117103 // 其他情况使用边用边更新
118- return Strategies .STALE_WHILE_REVALIDATE (params )
104+ return Strategies .STALE_WHILE_REVALIDATE (handler , context , next )
119105 }
120106}
121107```
0 commit comments