Skip to content

Commit

Permalink
feat(logger): now it will log hit cache when response cache is hit
Browse files Browse the repository at this point in the history
  • Loading branch information
JOU-amjs committed Jun 28, 2023
1 parent cfcfa69 commit 9ccdc82
Show file tree
Hide file tree
Showing 16 changed files with 253 additions and 39 deletions.
1 change: 0 additions & 1 deletion src/Alova.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { trueValue } from './utils/variables';

type AlovaMethodCreateConfig<R, T, RC, RH> = Partial<MethodRequestConfig> & AlovaMethodConfig<R, T, RC, RH>;

export const alovas = [] as Alova<any, any, any, any, any>[];
const defaultAlovaOptions = {
/**
* GET请求默认缓存5分钟(300000毫秒),其他请求默认不缓存
Expand Down
15 changes: 13 additions & 2 deletions src/functions/sendRequest.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Method from '@/Method';
import defaultCacheLogger from '@/predefine/defaultCacheLogger';
import { matchSnapshotMethod, saveMethodSnapshot } from '@/storage/methodSnapShots';
import { getResponseCache, setResponseCache } from '@/storage/responseCache';
import { persistResponse } from '@/storage/responseStorage';
Expand All @@ -17,6 +18,7 @@ import {
newInstance,
noop,
promisify,
sloughFunction,
_self
} from '../utils/helper';
import {
Expand Down Expand Up @@ -89,7 +91,13 @@ export default function sendRequest<S, E, R, T, RC, RE, RH>(
response = () => {
// 每次请求时将中断函数绑定给method实例,使用者也可通过methodInstance.abort()来中断当前请求
methodInstance.abort = abort;
const { beforeRequest = noop, responsed, responded, requestAdapter } = getOptions(methodInstance),
const {
beforeRequest = noop,
responsed,
responded,
requestAdapter,
cacheLogger = defaultCacheLogger
} = getOptions(methodInstance),
// 使用克隆之前的method key,以免在beforeRequest中method被改动而导致method key改变
// method key在beforeRequest中被改变将会致使使用method 实例操作缓存时匹配失败
methodKey = key(methodInstance),
Expand All @@ -116,8 +124,12 @@ export default function sendRequest<S, E, R, T, RC, RE, RH>(
})
.then(cachedResponse => {
// 如果没有缓存则发起请求
const { e: expireTimestamp, s: toStorage, t: tag, m: cacheMode } = getLocalCacheConfigParam(clonedMethod);
if (cachedResponse !== undefinedValue) {
requestAdapterCtrlsPromiseResolveFn(); // 遇到缓存将不传入ctrls

// 打印缓存日志
sloughFunction(cacheLogger, defaultCacheLogger)(cachedResponse, clonedMethod, cacheMode, tag);
return cachedResponse;
}
fromCache = falseValue;
Expand All @@ -130,7 +142,6 @@ export default function sendRequest<S, E, R, T, RC, RE, RH>(
name: methodInstanceName = '',
shareRequest
} = getConfig(clonedMethod),
{ e: expireTimestamp, s: toStorage, t: tag } = getLocalCacheConfigParam(clonedMethod),
namespacedAdapterReturnMap = (adapterReturnMap[id] = adapterReturnMap[id] || {}),
// responsed是一个错误的单词,正确的单词是responded
// 在2.1.0+添加了responded的支持,并和responsed做了兼容处理
Expand Down
25 changes: 11 additions & 14 deletions src/functions/useHookToSendRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { getPersistentResponse } from '@/storage/responseStorage';
import { getStateCache, removeStateCache, setStateCache } from '@/storage/stateCache';
import createAlovaEvent from '@/utils/createAlovaEvent';
import {
exportFetchStates,
GeneralFn,
exportFetchStates,
getConfig,
getContext,
getHandlerMethod,
Expand All @@ -17,21 +17,21 @@ import {
isFn,
key,
noop,
sloughConfig
sloughConfig,
sloughFunction
} from '@/utils/helper';
import myAssert, { assertMethodMatcher } from '@/utils/myAssert';
import {
MEMORY,
PromiseCls,
STORAGE_RESTORE,
falseValue,
forEach,
len,
MEMORY,
nullValue,
promiseCatch,
PromiseCls,
promiseReject,
promiseResolve,
promiseThen,
STORAGE_RESTORE,
trueValue,
undefinedValue
} from '@/utils/variables';
Expand Down Expand Up @@ -83,7 +83,10 @@ export default function useHookToSendRequest<S, E, R, T, RC, RE, RH, UC extends
| FrontRequestHookConfig<S, E, R, T, RC, RE, RH>
| FetcherHookConfig,
{ id, options, storage } = getContext(methodInstance),
{ update } = options.statesHook,
{
statesHook: { update },
errorLogger
} = options,
// 如果是静默请求,则请求后直接调用onSuccess,不触发onError,然后也不会更新progress
methodKey = key(methodInstance),
{ e: expireMilliseconds, m: cacheMode, t: tag } = getLocalCacheConfigParam(methodInstance);
Expand Down Expand Up @@ -312,13 +315,7 @@ export default function useHookToSendRequest<S, E, R, T, RC, RE, RH, UC extends
// catch回调函数
(error: Error) => {
// 控制在输出错误消息
let errorLogger = options.errorLogger;
errorLogger = isFn(errorLogger)
? errorLogger
: ![falseValue, nullValue].includes(errorLogger as any)
? defaultErrorLogger
: undefinedValue;
errorLogger && errorLogger(error, methodInstance);
sloughFunction(errorLogger, defaultErrorLogger)(error, methodInstance);

const newStates = { error } as Partial<FrontRequestState<any, any, any, any, any>>;
// loading状态受控时将不再更改为false
Expand Down
3 changes: 1 addition & 2 deletions src/hooks/useFetcher.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { alovas } from '@/Alova';
import createRequestState from '@/functions/createRequestState';
import { filterSnapshotMethods } from '@/storage/methodSnapShots';
import { exportFetchStates, noop } from '@/utils/helper';
import { assertAlovaCreation, assertMethodMatcher } from '@/utils/myAssert';
import { falseValue, trueValue } from '@/utils/variables';
import { alovas, falseValue, trueValue } from '@/utils/variables';
import { FetcherHookConfig, FetcherType, MethodMatcher } from '~/typings';

/**
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useRequest.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import Alova, { alovas } from '@/Alova';
import Alova from '@/Alova';
import createRequestState from '@/functions/createRequestState';
import Method from '@/Method';
import { assertAlovaCreation } from '@/utils/myAssert';
import { trueValue } from '@/utils/variables';
import { alovas, trueValue } from '@/utils/variables';
import { AlovaMethodHandler, RequestHookConfig } from '~/typings';

export default function useRequest<S, E, R, T, RC, RE, RH>(
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useWatcher.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import Alova, { alovas } from '@/Alova';
import Alova from '@/Alova';
import createRequestState from '@/functions/createRequestState';
import Method from '@/Method';
import myAssert, { assertAlovaCreation } from '@/utils/myAssert';
import { len } from '@/utils/variables';
import { alovas, len } from '@/utils/variables';
import { Writable } from 'svelte/store';
import { WatchSource } from 'vue';
import { AlovaMethodHandler, SvelteWritable, VueRef, WatcherHookConfig } from '~/typings';
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { AlovaOptions } from '~/typings';
import Alova, { alovas } from './Alova';
import Alova from './Alova';
import { getStatesHook, newInstance } from './utils/helper';
import myAssert from './utils/myAssert';
import { pushItem } from './utils/variables';
import { alovas, pushItem } from './utils/variables';
export * from './functions/manipulateCache';
export { default as updateState } from './functions/updateState';
export { default as useFetcher } from './hooks/useFetcher';
Expand Down
18 changes: 18 additions & 0 deletions src/predefine/defaultCacheLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { CacheMode } from '~/typings';
import { Method } from '..';

const titleStyle = 'color: black; font-size: 12px; font-weight: bolder';
/**
* 默认cacheLogger函数
*/
export default (response: any, methodInstance: Method, cacheMode: CacheMode, tag: string | number | undefined) => {
const cole = console;
cole.groupCollapsed('%cHitCache', 'padding: 2px 6px; background: #c4fcd3; color: #53b56d;', methodInstance.url);
cole.log('%c[Mode]', titleStyle, cacheMode);
if (cacheMode === 'restore') {
cole.log('%c[Tag]', titleStyle, tag);
}
cole.log('%c[Method]', titleStyle, methodInstance);
cole.log('%c[Cache]', titleStyle, response);
cole.groupEnd();
};
3 changes: 1 addition & 2 deletions src/storage/responseStorage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { alovas } from '@/Alova';
import { getTime } from '@/utils/helper';
import { forEach, nullValue, pushItem } from '@/utils/variables';
import { alovas, forEach, nullValue, pushItem } from '@/utils/variables';
import { AlovaGlobalStorage } from '~/typings';

const responseStorageKeyPrefix = 'alova.';
Expand Down
6 changes: 4 additions & 2 deletions src/utils/helper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Alova, AlovaMethodHandler, CacheExpire, FrontRequestState } from '~/typings';
import { Alova, AlovaMethodHandler, CacheExpire, CacheMode, FrontRequestState } from '~/typings';
import Method from '../Method';
import myAssert from './myAssert';
import {
Expand Down Expand Up @@ -149,7 +149,7 @@ export const noop = () => {},
const _localCache = getConfig(methodInstance).localCache,
getCacheExpireTs = (_localCache: CacheExpire) =>
isNumber(_localCache) ? getTime() + _localCache : getTime(_localCache || undefinedValue);
let cacheMode = MEMORY,
let cacheMode: CacheMode = MEMORY,
expire = 0,
storage = falseValue,
tag: undefined | string = undefinedValue;
Expand Down Expand Up @@ -195,6 +195,8 @@ export const noop = () => {},
*/
sloughConfig = <T>(config: T | ((...args: any[]) => T), args: any[] = []) =>
isFn(config) ? config(...args) : config,
sloughFunction = <T, U>(arg: T | undefined, defaultFn: U) =>
isFn(arg) ? arg : ![falseValue, nullValue].includes(arg as any) ? defaultFn : noop,
/**
* 将targetFn转换为异步函数
* @param targetFn 目标函数
Expand Down
3 changes: 1 addition & 2 deletions src/utils/myAssert.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { alovas } from '@/Alova';
import { Method } from '..';
import alovaError from './alovaError';
import { len } from './variables';
import { alovas, len } from './variables';

/**
* 自定义断言函数,表达式为false时抛出错误
Expand Down
4 changes: 3 additions & 1 deletion src/utils/variables.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Alova } from '~/typings';
import { GeneralFn } from './helper';

// 以下为减少编译代码量而添加的统一处理函数或变量
Expand Down Expand Up @@ -35,4 +36,5 @@ export const PromiseCls = Promise as typeof Promise<any>,
// 缓存会持久化,且每次刷新会读取持久化缓存到内存中,这意味着内存一直会有缓存
STORAGE_RESTORE = 'restore',
// 是否为服务端渲染
isSSR = typeof window === 'undefined';
isSSR = typeof window === 'undefined',
alovas = [] as Alova<any, any, any, any, any>[];
Loading

0 comments on commit 9ccdc82

Please sign in to comment.