Skip to content

Instantly share code, notes, and snippets.

@lushijie
Last active November 1, 2018 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lushijie/d745b748ea24f6581a35102a18e99c4d to your computer and use it in GitHub Desktop.
Save lushijie/d745b748ea24f6581a35102a18e99c4d to your computer and use it in GitHub Desktop.
storage 调试
function datetime(date = new Date(), format) {
if (date && typeof date === 'string') {
const dateString = date;
date = new Date(Date.parse(date));
if (isNaN(date.getTime()) && !format) {
format = dateString;
date = new Date();
}
}
format = format || 'YYYY-MM-DD HH:mm:ss';
const fn = d => {
return ('0' + d).slice(-2);
};
const d = new Date(date);
const formats = {
YYYY: d.getFullYear(),
MM: fn(d.getMonth() + 1),
DD: fn(d.getDate()),
HH: fn(d.getHours()),
mm: fn(d.getMinutes()),
ss: fn(d.getSeconds())
};
return format.replace(/([a-z])\1+/ig, a => {
return formats[a] || a;
});
}
const DB = {
save: function(key, jsonData, expSecond){
const record = {
value: jsonData,
timestamp: !expSecond ? null : datetime(new Date().getTime() + expSecond * 1000)
};
localStorage.setItem(key, JSON.stringify(record));
return jsonData;
},
get: function(key, ignoreExp){
const record = JSON.parse(localStorage.getItem(key));
if (record) {
if (!ignoreExp && record.timestamp && new Date().getTime() > +new Date(record.timestamp)) {
return null;
}
return record.value;
}
return null;
},
debug: function fn(key, restart) {
let begin = {
value: {},
timestamp: null,
};
if (!restart) {
begin = JSON.parse(window.localStorage.getItem(key)) || begin;
}
window.localStorage.setItem(key, JSON.stringify(begin));
return function(action, jsonData) {
try {
let preObj = JSON.parse(window.localStorage.getItem(key));
preObj['value'][action] = jsonData;
preObj.timestamp = datetime();
window.localStorage.setItem(key, JSON.stringify(preObj));
return JSON.stringify(preObj)
} catch(e) {
console.warn(e);
}
}
}
}
// DB.save('a', {a: 123});
// DB.save('b', {a: 123}, 10);
// console.log(DB.get('a'), '---');
// DB.debug('sec')('a', {b: 123});
// console.log(DB.get('sec', true), '++++');
module.exports = DB;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment