Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.