Skip to content

Commit

Permalink
feat(Storage): 新增 getRemember 方法
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed May 22, 2019
1 parent 855e508 commit 696e62b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,29 @@ export class Storage<
return value
}

getRemember<DV extends T[K] | (() => (T[K] | Promise<T[K]>))>( // eslint-disable-line
key: K,
defaultValue: DV = null,
): Promise<T[K]> { // eslint-disable-line
return this.get(key, defaultValue).then(value => {
if (value != null) {
return this.set({ [key]: value }).then(() => value)
}
return value
})
}

getRememberSync<DV extends T[K] | (() => T[K])>( // eslint-disable-line
key: K,
defaultValue: DV = null,
): T[K] { // eslint-disable-line
const value = this.getSync(key, defaultValue)
if (value != null) {
this.setSync({ [key]: value })
}
return value
}

remove(key: K) {
return this.driver.remove(key)
}
Expand Down
7 changes: 7 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,13 @@ describe('Storage', () => {
storage.clearSync()
expect(storage.getSync('str')).toBeNull()
})

test('可记住获取的值', async () => {
expect(await storage.get('str')).toBeNull()
expect(await storage.getRemember('str', () => 'hello')).toBe('hello')
expect(storage.getSync('str', () => 'hello2')).toBe('hello')
expect(await storage.get('str')).toBe('hello')
})
})
})

Expand Down

0 comments on commit 696e62b

Please sign in to comment.