jy-safe-app/utils/request.js

255 lines
6.9 KiB
JavaScript
Raw Normal View History

2025-10-14 15:17:30 +08:00
import config from '../config/common' // 配置文件
import handle401 from './handle401'
// import MD5 from 'md5'
export default {
domain() {
// return config.uni_app_web_api_url.replace('api', '')
return config.uni_app_web_local_api_url.replace('api', '')
},
getRequestHeaders(url, type = 'post', isIgnoreTenant) {
const auth = 'Bearer ' + uni.getStorageSync('accessToken')
// const user = uni.getStorageSync('loginUserVerify')
// const RootOrgId = uni.getStorageSync('RootOrgId')
const appInfoData = uni.getStorageSync('appInfo')
const tenant = uni.getStorageSync('Tenant') || ''
const userId = appInfoData?.User?.ID || ''
const userName = appInfoData?.User?.NAME || ''
const orgId = appInfoData?.User?.ORG_ID || ''
const dataRule = appInfoData?.DataRule ? appInfoData?.DataRule.join(',') : ''
const departmentId = appInfoData?.User?.DEPARTMENT_ID || ''
const mineType = appInfoData?.User?.MineType || ''
const headers = {
'Content-Type': type === 'post' ? 'application/json' : 'application/x-www-form-urlencoded',
Authorization: auth,
Tenant: tenant,
userid: userId,
// username: userName, // username不能使用中文放在header
departmentId,
MineType: mineType,
orgId,
DataRule: dataRule,
RequestType: '2'
}
// 非 OP 路径接口header 需要添加 Tenant
// const Tenant = uni.getStorageSync('Tenant')
// url.indexOf('OP') != 0 && !isIgnoreTenant && (headers.Tenant = Tenant)
return headers
},
send(options = {}, onlyData, isShowLoading) {
const u = config.serviceHost(options.url)
// loading加载
if (isShowLoading) {
uni.showLoading({
title: '加载中',
mask: true
})
}
// options.url = config.uni_app_web_api_url + '' + options.url
options.url = u
// 请求方式
options.method = options.method || 'GET'
// TODO:
// let users = uni.getStorage("users");
// if(users != null){
// options.header = { "Auth-Token" : users.token };
// }
// options.header = options.header
// 发起Promise请求
return new Promise((resolve, reject) => {
uni.request(options).then(async (res, err) => {
uni.hideLoading()
let {
errMsg,
data,
statusCode
} = res
// 登陆过期
if (statusCode === 401) {
const refreshData = await handle401(options)
errMsg = refreshData.errMsg
data = refreshData.data
statusCode = refreshData.statusCode
}
if (statusCode !== 200) {
if (statusCode === 400) {
uni.removeStorageSync('accessToken')
uni.removeStorageSync('refreshToken')
let pages = getCurrentPages()
if (pages.length > 0) {
let prevPage = pages[pages.length - 1]
if (prevPage.route !== 'pages/login/index') {
uni.navigateTo({
url: '/pages/login/index'
})
} else {
uni.showModal({
title: "400没有访问权限",
showCancel: false,
content: data.error_description
})
}
}
} else {
uni.showToast({
title: '请求错误: ' + statusCode,
icon: 'error'
})
}
return
}
if (errMsg !== 'request:ok') {
reject(errMsg)
} else {
uni.hideLoading()
// 相应拦截、根据后端的状态码来写,可以自行判断和封装
if (!data.IsSuccessful && onlyData) {
// wyw api 调用错误提示 需要用户确认 再消失
uni.showModal({
title: '错误提示',
content: data.ErrorMessage,
showCancel: false,
})
reject(data.ErrorMessage)
} else {
resolve(data)
}
}
})
})
},
upload(url = '', filePath) {
// return this.send({
// url: url,
// data: data,
// header: this.getRequestHeaders(url, 'post')
// }, onlyData)
const appInfoData = uni.getStorageSync('appInfo')
const tenant = uni.getStorageSync('Tenant') || ''
const userId = appInfoData?.User?.ID || ''
const orgId = appInfoData?.User?.ORG_ID || ''
return new Promise((resolve, reject) => {
uni.showLoading()
uni.uploadFile({
url: url,
filePath: filePath[0],
name: 'file',
formData: {
OrgId: orgId,
userID: userId
},
header: {
Tenant: tenant,
userid: userId
},
success: (res) => {
if (res.statusCode === 200) {
uni.hideLoading()
const uploadResult = JSON.parse(res.data)
uploadResult.isOnline = true
resolve(uploadResult)
if (uploadResult.IsSuccessful) {
uploadResult.Data.isOnline = true
resolve(uploadResult.Data)
} else {
reject(uploadResult.ErrorMessage)
}
}
},
fail: (err) => {
console.log(err)
}
})
})
},
get(url = '', data = {}, onlyData = true) {
return this.send({
url: url,
data: data,
header: this.getRequestHeaders(url, 'get')
}, onlyData)
},
post(url = '', data = {}, onlyData = true, isShowLoading = true) {
const DataRule = uni.getStorageSync('DataRule')
const dataStr = JSON.stringify(Object.assign({}, data, {
DataRule
}))
// const requestKey = url + '_' + MD5(dataStr) + '_requestKey'
// TODO: 节流
// const loaded = uni.getStorageSync(requestKey)
// if (loaded) return null
// uni.setStorageSync(requestKey, true)
return this.send({
url: url,
data: data,
header: this.getRequestHeaders(url, 'post'),
method: 'POST'
}, onlyData, isShowLoading)
},
// 处理缓存数据
processCachedData(url) {
try {
//数据处理
var riskUpInfo = uni.getStorageSync('riskUpInfo') || [];
if (riskUpInfo.length === 0) return;
var thisRiskUp = riskUpInfo.filter(e => e.RISK_AREA_ID && e.RISK_AREA_ID.length > 0)
var maxLength = thisRiskUp.length
if (maxLength === 0) return;
// 3个一组 往服务端传
var listOperate = []
const appInfoData = uni.getStorageSync('appInfo')
const tenant = uni.getStorageSync('Tenant') || ''
const userId = appInfoData?.User?.ID || ''
const orgId = appInfoData?.User?.ORG_ID || ''
const auth = 'Bearer ' + uni.getStorageSync('accessToken')
thisRiskUp.forEach((e, index) => {
e.USER_ID = userId
e.ORG_ID = orgId
e.OrgId = orgId
e.RiskContentState = 15
uni.uploadFile({
url: url,
filePath: e.filePath,
name: 'file',
data: e,
formData: e,
header: {
Tenant: tenant,
userid: userId,
Authorization: auth,
RequestType: '2'
},
success: (res) => {
if (res.statusCode == 200) {
var data = JSON.parse(res.data)
if (data.Data.imgFileID && data.Data.imgFileID.length > 0) {
//缓存删除
var riskUpInfo = uni.getStorageSync('riskUpInfo')
var riskUpInfoResult = riskUpInfo.filter(e => e.imgFileID != data.Data.imgFileID)
if (riskUpInfoResult == null || riskUpInfoResult.length == 0) {
uni.removeStorageSync('riskUpInfo');
} else
uni.setStorageSync('riskUpInfo', riskUpInfoResult);
}
}
},
fail: (err) => {
console.log(err)
}
})
})
} catch (e) {
//TODO handle the exception
}
},
}