67 lines
2.2 KiB
JavaScript
67 lines
2.2 KiB
JavaScript
const { ADMIN_API_BASE_URL, REQUEST_TIMEOUT } = require('./config')
|
|
const auth = require('./auth')
|
|
|
|
function buildUrl(url, params) {
|
|
const query = Object.keys(params || {})
|
|
.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
|
|
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
|
.join('&')
|
|
const baseUrl = params && params.__baseUrl ? params.__baseUrl : ADMIN_API_BASE_URL
|
|
if (params && params.__baseUrl) {
|
|
delete params.__baseUrl
|
|
}
|
|
const target = `${baseUrl}${url}`
|
|
return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target
|
|
}
|
|
|
|
function normalizeError(message, raw) {
|
|
const error = new Error(message || '请求失败')
|
|
error.raw = raw
|
|
return error
|
|
}
|
|
|
|
function request(options) {
|
|
const method = String(options.method || 'GET').toUpperCase()
|
|
const token = auth.getAccessToken()
|
|
return new Promise((resolve, reject) => {
|
|
wx.request({
|
|
url: buildUrl(options.url, options.params),
|
|
method,
|
|
timeout: options.timeout || REQUEST_TIMEOUT,
|
|
data: method === 'GET' ? undefined : options.data,
|
|
header: {
|
|
'Content-Type': 'application/json',
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
...(options.header || {})
|
|
},
|
|
success(response) {
|
|
if (response.statusCode === 401) {
|
|
auth.clearSession()
|
|
wx.reLaunch({ url: '/pages/login/index' })
|
|
reject(normalizeError('登录已失效,请重新登录', response))
|
|
return
|
|
}
|
|
if (response.statusCode >= 400) {
|
|
reject(normalizeError((response.data && response.data.message) || '网络请求失败', response))
|
|
return
|
|
}
|
|
const payload = response.data
|
|
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
|
|
if (payload.code === 200) {
|
|
resolve(payload.data)
|
|
return
|
|
}
|
|
reject(normalizeError(payload.message || '请求失败', payload))
|
|
return
|
|
}
|
|
resolve(payload)
|
|
},
|
|
fail(error) {
|
|
reject(normalizeError(error.errMsg || '网络异常', error))
|
|
}
|
|
})
|
|
})
|
|
}
|
|
|
|
module.exports = request
|