Skip to content

Commit 7eda09b

Browse files
committed
fix(Cache): remove cached items when expired
1 parent e5f55a6 commit 7eda09b

File tree

3 files changed

+23
-11
lines changed

3 files changed

+23
-11
lines changed

src/cache.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
const storage = require('./localstorage');
33
const AV = require('./av');
44

5+
const remove = exports.remove = storage.removeItemAsync.bind(storage);
6+
57
exports.get = (key) => {
68
return storage.getItemAsync(`${AV.applicationId}/${key}`)
79
.then(cache => {
@@ -15,6 +17,7 @@ exports.get = (key) => {
1517
if (!expired) {
1618
return cache.value;
1719
}
20+
return remove(key).then(() => null);
1821
}
1922
return null;
2023
});

src/utils.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ const init = (AV) => {
131131

132132
const setRegionServer = (region = 'cn') => {
133133
AVConfig.region = region;
134-
// 如果用户在 init 之前设置了 APIServerURL,则跳请求 router
134+
// 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router
135135
if (AVConfig.APIServerURL) {
136136
return;
137137
}
@@ -144,7 +144,10 @@ const init = (AV) => {
144144
return ajax('get', `https://app-router.leancloud.cn/1/route?appId=${AV.applicationId}`)
145145
.then(servers => {
146146
if (servers.api_server) {
147-
Cache.set('APIServerURL', servers.api_server, (servers.ttl || 3600) * 1000);
147+
Cache.set(
148+
'APIServerURL',
149+
servers.api_server,
150+
(typeof servers.ttl ==='number' ? servers.ttl : 3600) * 1000);
148151
return servers.api_server;
149152
}
150153
});

test/cache.js

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
11
var Cache = AV.Cache;
2-
const wait = time => new Promise(resolve => setTimeout(resolve, time));
2+
var wait = function wait(time) {
3+
return new Promise(function (resolve) {
4+
return setTimeout(resolve, time);
5+
});
6+
};
37

4-
describe('Cache', () => {
5-
const getValue = () => Cache.get('__test');
6-
it('get/set', () =>
7-
Cache.set('__test', 1).then(getValue).then(value => {
8+
describe('Cache', function () {
9+
var getValue = function getValue() {
10+
return Cache.get('__test');
11+
};
12+
it('get/set', function () {
13+
return Cache.set('__test', 1).then(getValue).then(function (value) {
814
expect(value).to.be(1);
915
return Cache.set('__test', '1', 100).then(getValue);
10-
}).then(value => {
16+
}).then(function (value) {
1117
expect(value).to.be('1');
1218
return wait(110).then(getValue);
13-
}).then(value => {
19+
}).then(function (value) {
1420
expect(value).to.be(null);
15-
})
16-
);
21+
});
22+
});
1723
});

0 commit comments

Comments
 (0)