export default class {
constructor (storage, options) {
this.storage = storage;
this.options = Object.assign({
namespace: ''
}, options || {});
Object.defineProperty(this, 'length', {
get () {
return this.storage.length;
}
});
}
set (name, value, expire = null) {
this.storage.setItem(
this.options.namespace + name,
JSON.stringify({value: value, expire: expire !== null ? new Date().getTime() + expire : null})
);
}
get (name, def = null) {
let item = this.storage.getItem(this.options.namespace + name);
if (item !== null) {
let data = JSON.parse(item);
if (data.expire === null) {
return data.value;
}
Iif (data.expire >= new Date().getTime()) {
return data.value;
}
this.remove(name);
}
return def;
}
key (index) {
return this.storage.key(index);
}
remove (name) {
return this.storage.removeItem(this.options.namespace + name);
}
clear () {
Iif (this.length === 0) {
return;
}
for (let i = 0; i < this.length; i++) {
let key = this.storage.key(i);
let regexp = new RegExp(`^${this.options.namespace}.+`, 'i');
Iif (regexp.test(key) === false) {
continue;
}
this.storage.removeItem(key);
}
}
}
|