CacheData.ets
2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { DateTimeUtils, StringUtils } from 'wdKit/Index';
import { CacheDataSaveUtil } from './CacheDataSaveUtil';
import { JSON } from '@kit.ArkTS';
/**
* 接口数据存储封装类
*/
export class CacheData {
/**
* 底部导航栏缓存的数据key
*/
static bottomCacheKey = 'bottom_cache_data_key'
/**
* 头部频道缓存的数据key
*/
static channelCacheDataKey = 'channel_data_cache_id_'
/**
* 页面page组件的数据key
*/
static comPageInfoCacheKey = 'com_pageInfo_cache_id_'
/**
* 页面组件的数据key
*/
static compGroupInfoDataCacheKey = 'com_data_info_cache_id_'
// 接口返回数据
networkData?: object;
// 数据更新时间戳
updateTimeInMillis: number = 0;
// 接口返回md5,用于判断接口数据是否更新
md5: string = '';
constructor(md5: string, timeMillis: number, networkData: object) {
this.md5 = md5
this.updateTimeInMillis = timeMillis
this.networkData = networkData
}
/**
* 根据新旧md5值进行判断,是否需要刷新数据
* @param responseMd5 新值,接口返回
* @returns
*/
needRefreshByMd5(responseMd5: string): boolean {
if (StringUtils.isEmpty(this.md5) || StringUtils.isEmpty(responseMd5)) {
return false
}
return this.md5 != responseMd5
}
static saveCacheData(cacheKey: string, data: object, responseMd5: string) {
if (!data) {
return
}
let time = DateTimeUtils.getTimeStamp()
let cacheData = new CacheData(responseMd5, time, data)
CacheDataSaveUtil.save(cacheKey, JSON.stringify(cacheData))
}
/**
* 获取缓存数据
*/
static getLocalCacheData(key: string): Promise<CacheData | null> {
return new Promise<CacheData | null>((success) => {
if (StringUtils.isEmpty(key)) {
success(null)
return
}
CacheDataSaveUtil.get(key).then((data) => {
let str = data as string
let cache = JSON.parse(str) as CacheData
success(cache)
}).catch(() => {
success(null)
})
})
}
static getNetworkDataSync(data: CacheData): string {
if (data.networkData) {
return JSON.stringify(data.networkData);
}
return "";
}
static getNetworkDataAsync(data: CacheData): Promise<string> {
return new Promise((resolve) => {
let string = ""
if (data.networkData) {
string = JSON.stringify(data.networkData);
}
resolve(string)
})
}
}