小程序缓存API解决方案

为了避免给服务器造成过大压力,造成资源浪费,我们可以将一些 API 数据缓存在客户端本机中。这种缓存的对象应该具有以下特点:

  1. 数据量少。
  2. 及时性要求不高,不需要实时更新。
  3. 数据较为固定。

对于缓存 API 的方案,分为两种。一是单独封装工具供开发者调用,二是在 http 请求工具中使用缓存代理

单独封装工具

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
const cacheTool = {
/**
*
* @param {string} key 键名
* @param {any} data 缓存的数据
* @param {number} second 需要缓存的时间,以秒为单位
*/
setItem: function (key, data, second) {
const expireTime = new Date().getTime() + Number(second) * 1000;
wx.setStorageSync(key, { data, expireTime });
},
getItem: function (key) {
if (_this._isSet(key)) {
const isNotExpire = new Date().getTime() <= cache.expireTime;
if (isNotExpire) {
const cache = wx.getStorageSync(key);
return { valid: true, data: cache.data };
} else {
return { valid: false };
}
} else {
return { valid: false };
}
},
_isSet: function (key) {
const cache = wx.getStorageSync(key);
return cache !== "";
},
};

调用

1
2
3
4
5
6
7
8
9
10
const cache = cacheTool.getItem("name");
if (cache.valid) {
this.setData({
list: cache.data,
});
} else {
// http request
// ...
cacheTool.setItem("name", data, 600); // 设置10分钟缓存
}

在 http 工具中使用缓存代理

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
//	https.js
// TODO:仍需改进
const baseURL = "https://nufm.dfcfw.com/EM_Finance2014NumericApplication";
const cacheTool = require("../util/cacheTool.js");
const http = ({ url, data, method = "get", cache = false, expire = 600, cacheKey = "_" }) => {
return new Promise((resolve, reject) => {
if (cache) {
const cache = cacheTool.getItem(cacheKey);
if (cache.valid) {
resolve(cache.data);
} else {
httpRequest(url, data, method, cache, expire, cacheKey)
.then((res) => {
resolve(res);
})
.catch((err) => {
reject(err);
});
}
} else {
httpRequest(url, data, method, cache)
.then((res) => {
resolve(res);
})
.catch((err) => {
reject(err);
});
}
});
};

const httpRequest = (url, data, method, cache, expire, cacheKey) => {
return new Promise((resolve, reject) => {
wx.request({
url: `${baseURL}/${url}`,
data,
method,
header: {
"content-type": "application-json",
},
complete: function (res) {
if (res.statusCode >= 200 && res.statusCode < 300) {
if (cache) {
cacheTool.setItem(cacheKey, res, expire);
}
resolve(res.data);
} else {
reject(res);
}
},
});
});
};
module.exports = http;
1
2
3
4
5
6
7
8
9
10
11
//	调用
http({
url:
"JS.aspx?type=CT&cmd=BK04781&sty=DCFFMBFMS&st=&sr=&p=&ps=&cb=&js=result37523225((x))&token=0b9469e9fdfd123fcec4532ae1c20f4f&callback=result37523225&_=1574835480421",
cache: true,
expire: 10,
cacheKey: "test",
data: "book_id=947&4id=914372&sky=fd732789509e52a2169d58f8959af7c8&t=1574836186&_type=ajax&rndval=1574834470633",
}).then((res) => {
console.log("res", JSON.stringify(res));
});
0%