实现缓存功能
parent
78addb6d96
commit
d5a6196d5b
@ -0,0 +1,88 @@
|
||||
import { RepositorySearchResultItem } from '../../api/api'
|
||||
|
||||
interface CacheWrapper<T> {
|
||||
[keyword:string]:Caches<T>
|
||||
}
|
||||
|
||||
interface Caches<T> {
|
||||
total_page:number
|
||||
list:{[page:number]:T[]}
|
||||
}
|
||||
|
||||
const cache:CacheWrapper<RepositorySearchResultItem> = {}
|
||||
|
||||
export function RepositorySearchCache (keyword:string, max_cache_count:number) {
|
||||
if (!cache[keyword]) {
|
||||
cache[keyword] = {
|
||||
list: [],
|
||||
total_page: 0
|
||||
}
|
||||
}
|
||||
|
||||
const _cache = cache[keyword]
|
||||
const _cache_list = _cache.list
|
||||
|
||||
return {
|
||||
|
||||
/**
|
||||
* 读取指定页码的缓存
|
||||
* @param {number} page 页码
|
||||
* @returns {RepositorySearchResultItem[]|undefined}
|
||||
*/
|
||||
read (page:number):RepositorySearchResultItem[]|undefined {
|
||||
return _cache_list[page]
|
||||
},
|
||||
|
||||
/**
|
||||
* 添加指定页码的缓存
|
||||
* @param {number} page 页码
|
||||
* @param {RepositorySearchResultItem[]} data 缓存数据
|
||||
* @returns {this}
|
||||
*/
|
||||
add (page:number, data:RepositorySearchResultItem[]) {
|
||||
if (!_cache_list[page] && this.getCount() >= max_cache_count) {
|
||||
this.remove(
|
||||
parseInt(Object.keys(_cache_list).shift()!, 10)
|
||||
)
|
||||
}
|
||||
_cache_list[page] = data
|
||||
return this
|
||||
},
|
||||
|
||||
/**
|
||||
* 移除指定页码的缓存
|
||||
* @param {number} page 页码
|
||||
* @returns {this}
|
||||
*/
|
||||
remove (page:number) {
|
||||
delete _cache_list[page]
|
||||
return this
|
||||
},
|
||||
|
||||
/**
|
||||
* 更新页码总数的缓存
|
||||
* @param {number} total 页码总数
|
||||
* @returns {this}
|
||||
*/
|
||||
updateTotalPage (total:number) {
|
||||
_cache.total_page = total
|
||||
return this
|
||||
},
|
||||
|
||||
/**
|
||||
* 获取页码总数缓存
|
||||
* @returns {number}
|
||||
*/
|
||||
getTotalPage ():number {
|
||||
return _cache.total_page
|
||||
},
|
||||
|
||||
/**
|
||||
* 获取当前缓存总数
|
||||
* @returns {number}
|
||||
*/
|
||||
getCount ():number {
|
||||
return Object.keys(_cache_list).length
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue