analytics.js 1.75 KB
import { toPromiseWX } from './wx'
const networkPromise = toPromiseWX('getNetworkType');

const ANALYTICS_KEYS = {
  WX_LOGIN_ERROR: 'wx_login_error',
  GET_USER_INFO_ERROR: 'get_userinfo_error',
  GET_PHONENUMBER_ERROR: 'get_phonenumber_error',
  SIGNIN_BY_OPENID_ERROR: 'signin_by_openid_error',
  DECODE_USERINFO_ERROR: 'decode_userinfo_error',
  SHOW_BIND_PHONE_NUMBER_PAGE: 'show_bind_phone_number_page',
  REQUEST_401_ERROR: 'request_401_error',
  REQUEST_508_ERROR: 'request_508_error',
  SET_STORAGE_ERROR: 'set_storage_error',
  GET_STORAGE_ERROR: 'get_storage_error'
}

export default class Analytics {
  constructor() {
    this._udid = this._getUdid();
    this.keys = ANALYTICS_KEYS;
    this._systemInfo = wx.getSystemInfoSync();
  }

  _getUdid() {
    return wx.getStorageSync('udid');
  }

  _getTime(date) {
    return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
  }

  _getTimeStamp(date) {
    return date.getTime();
  }

  async _getInfo(dataInfo = {}) {
    let res = await networkPromise();
    let info = { ...dataInfo };
    if (res.networkType) {
      info.network = res.networkType;
    }
    let systemInfo = this._systemInfo;
    if (systemInfo) {
      info.os_version = systemInfo.system;
      info.device_model = systemInfo.model;
      info.device_brand = systemInfo.brand;
      info.sdk_version = systemInfo.SDKVersion;
    }
    return info;
  }
  
  async report(key, data) {
    try {
      let date = new Date();
      let newData = Object.assign({
        time: this._getTime(date),
        timestamp: this._getTimeStamp(date),
        udid: this._udid,
      }, data);
      let info = await this._getInfo(data.info);
      newData.info = JSON.stringify(info);
      wx.reportAnalytics(key, newData);
    } catch (error) {

    }
  }
}