sendStrategy.ts 2.48 KB
import storage from './loggerAndStorage'

class AsyncSendStrategy {
  public callback: (() => void) | null = null
  public sendTime: number = 1000 * 5
  public sendNum: number = 10
  public dataHasSend: boolean = true
  public dataHasChange: boolean = false
  public syncStorage: boolean = false
  public failTime: number = 0
  public is_first_batch_write: boolean = true

  start(): void {
    this.batchInterval()
  }

  public batchInterval(): void {
    const _this = this

    function loopWrite(): void {
      setTimeout(() => {
        _this.batchWrite()
        loopWrite()
      }, 500)
    }

    function loopSend(): void {
      setTimeout(() => {
        _this.batchSend()
        loopSend()
      }, _this.sendTime * Math.pow(2, _this.failTime))
    }

    loopWrite()
    loopSend()
  }

  public batchWrite(): void {
    const _this = this

    if (this.dataHasChange) {
      if (this.is_first_batch_write) {
        this.is_first_batch_write = false
        setTimeout(() => {
          _this.batchSend()
        }, 1000)
      }

      this.dataHasChange = false

      if (this.syncStorage) {
        // storage.uploadTrack();
        // 缓存数据--uploadTrack
        // setStorageSync(STORAGE_PREPARE_DATA_KEY, tracker.store.mem.mdata);
      }
    }
  }

  public batchSend(): void {
    if (this.dataHasSend) {
      let data
      let len
      const mdata = storage.getTrack()

      if (mdata.length >= this.sendNum) {
        data = mdata.slice(0, this.sendNum)
      } else {
        data = mdata
      }

      len = data.length

      if (len > 0) {
        this.dataHasSend = false
        this.webRequest({
          data,
          len,
          success: this.batchRemove.bind(this),
          fail: this.sendFail.bind(this)
        })
      }
    }
  }

  public batchRemove(len: number): void {
    // 删除数据
    storage.removeTrack(undefined)
    this.dataHasSend = true
    this.dataHasChange = true
    this.batchWrite()
    this.failTime = 0
  }

  public sendFail(): void {
    this.dataHasSend = true
    this.failTime++
  }

  public webRequest(option: { data: any; len: number; success: (len: number) => void; fail: () => void }): void {
    // if (option.data.length > 0) {
    //     const data = kit.batchTrackData(option.data);
    //     logger.info('上报数据监控:', decodeURIComponent(data));
    //     const temp = JSON.parse(decodeURIComponent(data));
    //     uploadStroageData(temp, option);
    // } else {
    //     option.success(option.len);
    // }
  }
}