如何解决我是否可以确保其他参数相同的函数不会调用该函数?
我写了一个小服务来缓存返回可观察值的请求。看起来像这样:
export class CacheService {
private readonly cacheMap = new Map<string,Observable<any>>();
public cachify<T>(
cacheKey: string,cacheableFunction: () => Observable<T>
): Observable<T> {
const existingCacheItem = this.cacheMap.has(cacheKey);
if (!existingCacheItem) {
this.cacheMap.set(cacheKey,cacheableFunction().pipe(shareReplay()));
}
return this.cacheMap.get(cacheKey);
}
}
然后在类似这样的组件中使用它:
getNodes(): Observable<Node[]> {
return this.cacheService.cachify('nodes|all',() =>
this.http.get<Knotenpunkt[]>('/api/v1/node')
);
}
getNodeById(id: number): Observable<Node> {
return this.cacheService.cachify(`nodes|${id}`,() =>
this.http.get<Knotenpunkt>('/api/v1/node/' + id)
);
}
现在是问题:开发人员有可能两次使用相同的cacheKey
(目的不同!)。这将是有问题的,因为它将覆盖缓存的内容,从而为使用的函数提供错误的值。有什么办法可以让我控制这一点?
我知道这是一个“开发人员问题”,但是在服务中处理该问题会很高兴。
代码中的问题案例:
this.cacheService.cachify('key-a',functionThatReturnsString);
// should work,because it's a new key
this.cacheService.cachify('key-b',functionThatReturnsNumber);
// should not work,because it's an already used key and returns a number (instead of a string like the first)
this.cacheService.cachify('key-a',functionThatReturnsNumber);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。