-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #95 from SeanMcGrath/local-storage
- Loading branch information
Showing
3 changed files
with
114 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
const ttl = 10 * 60 * 1000 // 10 mins | ||
const topLevelKey = "APP" | ||
|
||
function getTopLevel() { | ||
const topLevel = localStorage.getItem(topLevelKey) | ||
return topLevel ? JSON.parse(topLevel) : null | ||
} | ||
|
||
export default class LocalStorage { | ||
|
||
static set(key, value) { | ||
const now = new Date() | ||
const item = { | ||
value, | ||
expiry: now.getTime() + ttl | ||
} | ||
|
||
const current = getTopLevel() || {} | ||
current[key] = item | ||
|
||
localStorage.setItem(topLevelKey, JSON.stringify(current)) | ||
} | ||
|
||
static get(key) { | ||
let state = getTopLevel() | ||
if (!state) { | ||
return null | ||
} | ||
|
||
const item = state[key] | ||
if (!item) { | ||
return null | ||
} | ||
|
||
const now = new Date() | ||
if (now.getTime() > item.expiry) { | ||
delete state[key] | ||
localStorage.setItem(topLevelKey, state) | ||
return null | ||
} | ||
|
||
return item.value | ||
} | ||
|
||
// reset TTL | ||
static touch(key) { | ||
const currentValue = LocalStorage.get(key) | ||
if (currentValue) { | ||
LocalStorage.set(key, currentValue) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters