web.js 1.51 KB
/*
 * @Author: limin
 * @Date: 2018-06-23 11:13:44
 * @Last Modified by: limin
 * @Last Modified time: 2018-08-31 18:28:26
 */

const TYPE = {
    LOCAL: 'localStorage',
    SESSION: 'sessionStorage'
  }
  function isObject(val) {
    return val !== null && typeof val === 'object'
  }
  function encrypt(val) {
    if (!val) return val
    return val
  }
  
  function decrypt(val) {
    if (!val) return val
    return val
  }
  function set(key, val, type = TYPE.LOCAL) {
    if (isObject(val)) window[type].setItem(key, JSON.stringify(val))
    else window[type].setItem(key, encrypt(val))
  }
  function get(key, type = TYPE.LOCAL) {
    var val = window[type].getItem(key)
    try {
      if (val && val.startsWith('#')) {
        return val
      }
      const value = isObject(val)?JSON.parse(decrypt(val)):decrypt(val)
      return value
    } catch (e) {
      throw e
    }
  }
  function remove(key, type = TYPE.LOCAL) {
    window[type].removeItem(key)
  }
  function setSession(key, val, ex = 20) {
    set(key, val, TYPE.SESSION)
  }
  function getSession(key) {
    return get(key, TYPE.SESSION)
  }
  function removeSession(key) {
    remove(key, TYPE.SESSION)
  }
  // 默认30minute
  function setExpire(key, val, ex = 1.8e6) {
    set(key, { v: val, t: Date.now() + ex })
  }
  function getExpire(key) {
    var obj = get(key)
    if (obj.t > Date.now()) return obj.v
    else return null
  }
  export default {
    set,
    get,
    remove,
    setSession,
    getSession,
    removeSession,
    setExpire,
    getExpire
  }