data-utils.js 3.04 KB
import uuid from '../vendors/uuid'
export default {
  globalData: {},
  config: {},
  setApp(app) {
    this.globalData = app.globalData;
  },
  setConfig(data) {
    this.setGlobalData('config', data)
  },
  getConfig() {
    return this.getGlobalDataByKey('config')
  },
  getStorageSync(key,fromPage = 'app') {
    try {
      var value = wx.getStorageSync(key)
      if (value) {
        return value
      }
    } catch (e) {
      wx.reportAnalytics('get_storage_error', {
        key: key,
        error: e.message,
        error_code: e.code,
        from_page: fromPage,
      });
      console.log(`wx.getStorageSync get ${key} failed.`)
      return null;
    }
  },
  removeStorageSync(key) {
    try {
      wx.removeStorageSync(key)
    } catch (e) {
      console.log(`wx.removeStorageSync del ${key} failed.`)
    }
  },
  clearUserSession(arr) {
    const clearKeys = [
      'userInfo',
      ...arr
    ];

    clearKeys.forEach(key => {
      this.globalData[key] && this.setGlobalData(key,'')
    });
  },
  /**
   * 按变量名存储数据到globalData及缓存
   * @param name string
   * @param data string / object
   * @param isStorage Boolean
   */
  setGlobalData(name, data, isStorage = true) {
    if (typeof data === 'object' && Object.keys(data).length !== 0) {
      this.globalData[name] = {...this.globalData[name], ...data}
    } else {
      this.globalData[name] = data
    }
    isStorage && wx.setStorage({
      key: name,
      data: this.globalData[name]
    })
    
  },
  getGlobalDataByKey(name) { // 先从globalData中获取 没有则从缓存取并赋值给globalData
    let gVal = this.globalData[name]
    if (typeof gVal === 'object' && Object.keys(gVal).length !== 0) {
      return gVal
    }else if(typeof gVal === 'string' && gVal !== '') return gVal

    let value = this.getStorageSync(name)
    if (value) {
      this.globalData[name] = value
    }
    return value
  },
  isLogin: function () {
    return this.globalData.userInfo.uid > 0 ? true : false
  },
  getUid: function () {
    let userInfo = this.getGlobalDataByKey('userInfo');
    return userInfo && userInfo.uid || 0;
  },
  setUdid() {
    let udid = uuid().replace(/-/g, '')
    this.setGlobalData('udid', udid)
  },
  setSystemInfo() {
    try {
      const res = wx.getSystemInfoSync()
      this.setGlobalData('systemInfo',res)
    } catch (e) {
      // Do something when catch error
    }
  },
  getNetworkType() {
    return new Promise(resolve => {
      wx.getNetworkType({
        success: function (res) {
          let net = '0'
          let networkType = res.networkType
          if (networkType === 'wifi') {
            net = '1';
          } else if (networkType === '2g') {
            net = '2';
          } else if (networkType === '3g') {
            net = '3';
          } else if (networkType === '4g') {
            net = '4';
          } else {
            net = '0';
          }
          resolve(net)
        }
      })
    })
    
  }
  
}