Files
rlz/coupon/utils/request.js

90 lines
2.2 KiB
JavaScript
Raw Normal View History

/**
* 通用网络请求工具
* - 自动 loading / hideLoading
* - 自动 fail 错误提示
* - Promise 风格支持 async/await
* - code != 200 自动 toast reject
*/
const app = getApp()
// 请求计数,支持并发 loading
let requestCount = 0
/**
* @param {object} opts
* @param {string} opts.url - API 路径不含 baseUrl
* @param {string} opts.method - GET/POST默认 GET
* @param {object} opts.data - 请求参数
* @param {boolean} opts.loading - 是否显示 loading默认 true
* @param {string} opts.loadingText - loading 文案默认 "加载中..."
* @param {boolean} opts.showError - 失败时是否自动 toast默认 true
* @param {object} opts.header - 自定义 header会合并默认 header
* @returns {Promise<object>} res.data - 响应体 { code, msg, data }
*/
function request(opts) {
const {
url,
method = 'GET',
data = {},
loading = true,
loadingText = '加载中...',
showError = true,
header = {}
} = opts
if (loading) {
if (requestCount === 0) {
wx.showLoading({ title: loadingText, mask: true })
}
requestCount++
}
return new Promise((resolve, reject) => {
wx.request({
url: app.globalData.url + url,
method,
data,
header: {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + app.getCache('token'),
...header
},
success(res) {
if (res.data.code === 200) {
resolve(res.data)
} else {
if (showError) {
wx.showToast({
title: res.data.msg || '请求失败',
icon: 'none',
duration: 2000
})
}
reject(res.data)
}
},
fail(err) {
if (showError) {
wx.showToast({
title: '网络异常,请稍后重试',
icon: 'none',
duration: 2000
})
}
reject(err)
},
complete() {
if (loading) {
requestCount--
if (requestCount <= 0) {
requestCount = 0
wx.hideLoading()
}
}
}
})
})
}
module.exports = { request }