Skip to content

Commit

Permalink
feat(storage): support expire
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 31, 2018
1 parent 2dc3080 commit cf4333f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
21 changes: 15 additions & 6 deletions src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,14 @@ const storage = {
*
* @param key 键名
* @param value 键值
* @param expire 过期时间
*/
set(key: string, value: any): void {
set(key: string, value: any, expire?: Date): void {
if (value != null) {
storageDriver.set(key, JSON.stringify(value))
storageDriver.set(key, JSON.stringify({
expire: expire && expire.getTime(),
value
}))
}
},

Expand All @@ -53,11 +57,16 @@ const storage = {
* @returns 获取到的键值
*/
get(key: string): any {
let value = null
try {
value = JSON.parse(storageDriver.get(key))
} catch (err) {}
return value
const { expire, value = null } = JSON.parse(storageDriver.get(key))
if (expire && expire < new Date().getTime()) {
storage.remove(key)
return null
}
return value
} catch (_) {
return null
}
},

/**
Expand Down
18 changes: 17 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,22 @@ describe('storage', () => {
vtils.storage.clear()
expect(vtils.storage.get('hello')).toBeNull()
})
test('过期时间', done => {
expect(vtils.storage.get('time')).toBeNull()
vtils.storage.set('time', '123')
expect(vtils.storage.get('time')).toBe('123')
const time = new Date()
time.setMilliseconds(time.getMilliseconds() + 1000)
vtils.storage.set('time', '1234', time)
expect(vtils.storage.get('time')).toBe('1234')
setTimeout(() => {
expect(vtils.storage.get('time')).toBe('1234')
}, 900)
setTimeout(() => {
expect(vtils.storage.get('time')).toBeNull()
done()
}, 1001)
})
})

describe('randomString', () => {
Expand All @@ -845,7 +861,7 @@ describe('jsonp', () => {
test('ok', () => {
expect(
vtils.isPromise(
vtils.jsonp('https://jsonplaceholder.typicode.com/todos/1')
vtils.jsonp('https://jsonplaceholder.typicode.com/todos/1', { test: 1 })
)
).toBeTruthy()
})
Expand Down

0 comments on commit cf4333f

Please sign in to comment.