All files / src storage.js

85.19% Statements 23/27
86.36% Branches 19/22
100% Functions 2/2
85.19% Lines 23/27
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67  1x 1x 1x       1x   4x         10x 10x           9x 9x   9x 7x   7x 6x     1x       1x     3x               2x       1x       1x 1x 1x   1x       1x        
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);
    }
  }
}