httpApi.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import request from "./index";
  2. import {getObjValue} from "js-fast-way"
  3. //封装的请求
  4. export const httpApi = async (obj) => {
  5. return new Promise((resolve) => {
  6. //发起请求
  7. request(obj).then(async (response) => {
  8. resolve(await getResData(response, false))
  9. }).catch(async (response) => {
  10. resolve(await getResData(response, true))
  11. })
  12. })
  13. }
  14. //处理数据
  15. const getResData = async (response, error = false) => {
  16. return new Promise((resolve) => {
  17. const { headers, data, config } = response
  18. const resData = getObjValue(data)
  19. const httpData = {
  20. response,
  21. res: data,
  22. data: resData?.data,
  23. code: resData?.code,
  24. msg: resData?.msg,
  25. status: response?.statusCode,
  26. headers: headers,
  27. message: getMsgVal(response),
  28. error: error,
  29. }
  30. //处理延迟响应
  31. if (error) {
  32. resolve(httpData)
  33. } else {
  34. const { startTime, endTime } = config.metadata
  35. if (config.isDelay) {
  36. const duration = endTime - startTime
  37. if (duration < 500) {
  38. setTimeout(() => {
  39. resolve(httpData)
  40. }, 1000 - duration)
  41. } else {
  42. resolve(httpData)
  43. }
  44. } else {
  45. resolve(httpData)
  46. }
  47. }
  48. })
  49. }
  50. //获取msg消息内容
  51. const getMsgVal = ({statusCode, data}) => {
  52. const { code, msg, error_description } = getObjValue(data)
  53. if (statusCode === 404) {
  54. return '服务器异常,请联系管理员!'
  55. }
  56. if (code === 500 || code === 504) {
  57. return '该功能正在升级优化,请联系管理员!'
  58. } else {
  59. return msg || error_description || '未知错误'
  60. }
  61. }