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

const aseKey = 'UkRPT0pp' //秘钥必须为:8/16/32位
const isPro = process.env.NODE_ENV !== 'production'
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 = JSON.parse(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
}