Skip to content

Commit

Permalink
fix: 忽略无效缓存 (#68)
Browse files Browse the repository at this point in the history
  • Loading branch information
aooiuu committed Aug 28, 2024
1 parent e74b17d commit c442dac
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
6 changes: 6 additions & 0 deletions packages/shared/src/controller/RuleManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ export class RuleManager extends BaseController {
cacheKey({ args }) {
const { filePath = '', chapterPath = '', ruleId = '' } = args[0];
return `content@${ruleId || '__local__'}@${md5(filePath)}@v3_${md5(chapterPath)}`;
},
verify(data: any) {
return !!data?.content?.length;
}
})
async content({ filePath, chapterPath, ruleId }: { ruleId: string; filePath: string; chapterPath: string }) {
Expand All @@ -79,6 +82,9 @@ export class RuleManager extends BaseController {
}
// 本地
const content = await createBookParser(filePath).getContent(chapterPath);

if (!content.length) throw new Error('获取内容失败');

return {
content
};
Expand Down
11 changes: 9 additions & 2 deletions packages/shared/src/decorators/create-cache-decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,14 @@ function isEmpty(data: any): boolean {
else return !Object.keys(data).length;
}

export interface DecoratorArgs {
ttl?: number;
cacheKey: (arg: { className: string; methodName: string; args: any[] }) => string;
verify?: (data: any) => boolean;
}

export function createCacheDecorator<T>(options: CreateCacheDecoratorOptions<T>) {
return (decoratorArgs: { ttl?: number; cacheKey: (arg: { className: string; methodName: string; args: any[] }) => string }): MethodDecorator => {
return (decoratorArgs: DecoratorArgs): MethodDecorator => {
return (_target: unknown, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<any>) => {
const fn = descriptor.value;

Expand All @@ -35,8 +41,9 @@ export function createCacheDecorator<T>(options: CreateCacheDecoratorOptions<T>)
}

const cachedResult = await options.getItem(cacheKey);
const verified = typeof decoratorArgs.verify !== 'function' || decoratorArgs.verify(cachedResult);

if (!isEmpty(cachedResult)) {
if (!isEmpty(cachedResult) && verified) {
return cachedResult;
} else {
const result = await fn.apply(this, args);
Expand Down

0 comments on commit c442dac

Please sign in to comment.