【前端】云工厂的纸掌柜app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

119 lines
3.3 KiB

import { isFunction } from '../is.js'
import env from '@/env/index.js'
const urlEnv = env === 'production' ? '' : `-${env}`
const uploadUrl = `https://api-ops-yyt${urlEnv}.qniao.cn/cloud-print-user-center/utils/uploadImage`
/**
* 定义的一个thenable对象
*/
class ErrorPromise {
then() {}
}
export default class Http {
constructor(config = {}, { reqInterceptor, resInterceptor, transformConfig } = {}) {
this.baseUrl = config.baseUrl
this.header = config.header || {
'content-type': 'application/json;charset=UTF-8'
}
this.requestOption = config.requestOption || {}
this.reqInterceptor = reqInterceptor
this.resInterceptor = resInterceptor
this.transformConfig = transformConfig
}
post(config, options) {
return this.request(
{
method: 'POST',
...config
},
options
)
}
get(config, options) {
return this.request(
{
method: 'GET',
...config
},
options
)
}
/**
* @param {Object} config 和请求相关的参数
* @param {Object} options 对请求数据进行额外处理的参数
*/
request(config, options) {
let conf = Object.assign({}, config)
const { transformConfig, reqInterceptor, resInterceptor } = this
if (transformConfig && isFunction(transformConfig)) {
conf = transformConfig(this, config)
}
let opt = Object.assign({}, this.requestOption, options)
if (reqInterceptor && isFunction(reqInterceptor)) {
conf = reqInterceptor(conf, opt)
}
return new Promise((resolve, reject) => {
uni.request({
url: conf.url,
data: conf.data,
header: conf.header,
method: conf.method,
success: (res) => {
let data = resInterceptor(res, opt)
if (!data) {
console.log('报错的请求参数:', conf)
reject(res)
return
}
// 服务器错误也会用then抛出,需要自己判断data==null
resolve(data)
},
fail: (err) => {
uni.showToast({
title: '发生未知错误,请联系客服'
})
reject(err)
}
})
}).catch((err) => {
// 吃掉请求产生的异常 后期可以记录
console.error('native response error', err)
return new ErrorPromise()
})
}
// config:{}
uploadFile(config, options) {
return new Promise((resolve, reject) => {
let conf = Object.assign({}, config)
conf.url = uploadUrl
const { reqInterceptor } = this
let opt = Object.assign({}, this.requestOption, options)
if (reqInterceptor && isFunction(reqInterceptor)) {
conf = reqInterceptor(conf, opt)
}
delete conf.header['Content-Type']
uni.uploadFile({
url: conf.url,
header: {
...conf.header,
image: config.data.filePath
// 'Content-Type': 'image/png'
},
filePath: config.data.filePath,
name: config.data.fileName || 'image',
formData: {
image: config.data.filePath
},
success: (res) => {
uni.hideLoading()
resolve(res.data)
},
fail: (err) => {
reject(err)
}
})
}).catch((err) => {
console.error('upload native err', err)
})
}
}