request.js 2.57 KB
import { secretKey, domain, path, sign } from './http.js'
import util from '../utils/util.js'
/**接口 */
class Request {
  get(method, data, noSignAttr) {
    return this.request('GET', method, data, noSignAttr)
  }
  post(method, data, noSignAttr) {
    return this.request('POST', method, data, noSignAttr)
  }
  request(RequestMethods, method, data, noSignAttr = []) {
    let _this = this
    return new Promise((resolve, reject) => {
      wx.showNavigationBarLoading()
      if (!data) data = {}
      let header =
        RequestMethods === 'POST'
          ? {
              'content-type': 'application/x-www-form-urlencoded'
            }
          : {}
      data = _this.getData(data, method, noSignAttr)
      wx.request({
        url: `${domain}${path}?method=${method}`,
        data,
        method: RequestMethods,
        header,
        dataType: 'json',
        responseType: 'text',
        success(response) {
          /**业务代码 */
          let {
            data: { code },
            data
          } = response
          if (code == 20 || code == 21) {
            wx.hideLoading()
            wx.showModal({
              title: '温馨提示',
              content: '登录过期,请重新登录。',
              showCancel: false,
              confirmText: '去登录',
              confirmColor: '#3582EE',
              success(res) {
                if (res.confirm) {
                  getApp().login(true)
                }
              }
            })
          } else {
            resolve(data)
          }
        },
        fail(error) {
          wx.hideLoading()
          console.error(`接口异常:${domain}${path}?method=${method}`, error)
          wx.showToast({
            title: '系统异常',
            icon: 'error'
          })
          reject(error)
          // if (fail && typeof fail == 'function') {
          //   fail(error, reject)
          // } else {
          // }
        },
        complete() {
          wx.stopPullDownRefresh()
          wx.hideNavigationBarLoading()
        }
      })
    })
  }
  getData(data, method, noSignAttr) {
    // let sessionId = util.getSessionId()
    // if (sessionId) data['sessionId'] = sessionId
    data['v'] = '1.0.0'
    data['method'] = method
    data['format'] = 'json'
    data['locale'] = 'zh_CN'
    data['source'] = 'dj-wechat'
    data['appKey'] = secretKey.appKey

    let obj = sign(data, secretKey.secret, noSignAttr)

    //data['sign'] = obj.sign;
    return obj
  }
}
export default new Request()