Last active
October 24, 2018 13:10
-
-
Save dysonspherelab/5fc082125fffac2c8bde306c3c0bde3f to your computer and use it in GitHub Desktop.
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
import * as moment from "moment"; | |
interface StorageObj { | |
expiry: moment.Moment; | |
} | |
export class LocalS { | |
save(key: string, data: any) { | |
let obj; | |
const expiryObj = { expiry: moment().add(7, "days") }; | |
obj = data instanceof Object ? { ...data, ...expiryObj } : { value: data, ...expiryObj }; | |
const dataString = JSON.stringify(obj); | |
localStorage.setItem(key, dataString); | |
return Promise.resolve(); | |
} | |
load(key: string) { | |
const dataString = localStorage.getItem(key); | |
return new Promise((resolve) => { | |
if (dataString) { | |
const dataObj: StorageObj = JSON.parse(dataString); | |
if (dataObj.expiry && moment(dataObj.expiry).isAfter(moment())) { | |
delete dataObj.expiry; | |
resolve(dataObj); | |
} | |
} | |
resolve(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment