12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- import request from "./index";
- import {getObjValue} from "js-fast-way"
- //封装的请求
- export const httpApi = async (obj) => {
- return new Promise((resolve) => {
- //发起请求
- request(obj).then(async (response) => {
- resolve(await getResData(response, false))
- }).catch(async (response) => {
- resolve(await getResData(response, true))
- })
- })
- }
- //处理数据
- const getResData = async (response, error = false) => {
- return new Promise((resolve) => {
- const { headers, data, config } = response
- const resData = getObjValue(data)
- const httpData = {
- response,
- res: data,
- data: resData?.data,
- code: resData?.code,
- msg: resData?.msg,
- status: response?.statusCode,
- headers: headers,
- message: getMsgVal(response),
- error: error,
- }
- //处理延迟响应
- if (error) {
- resolve(httpData)
- } else {
- const { startTime, endTime } = config.metadata
- if (config.isDelay) {
- const duration = endTime - startTime
- if (duration < 500) {
- setTimeout(() => {
- resolve(httpData)
- }, 1000 - duration)
- } else {
- resolve(httpData)
- }
- } else {
- resolve(httpData)
- }
- }
- })
- }
- //获取msg消息内容
- const getMsgVal = ({statusCode, data}) => {
- const { code, msg, error_description } = getObjValue(data)
- if (statusCode === 404) {
- return '服务器异常,请联系管理员!'
- }
- if (code === 500 || code === 504) {
- return '该功能正在升级优化,请联系管理员!'
- } else {
- return msg || error_description || '未知错误'
- }
- }
|