httpParamsFormatting.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import axios from 'axios'
  2. import { Loading, Message } from 'element-ui'
  3. import _ from 'lodash'
  4. export default function axiosFormatting (customConfig) {
  5. const newCustomConfig = replaceParams(customConfig)
  6. // 将请求头和请求参数的值转化为对象形式
  7. const httpConfig = {
  8. timeout: 1000 * 30,
  9. baseURL: '',
  10. headers: newCustomConfig.headers
  11. }
  12. // let loadingInstance = null // 加载全局的loading
  13. const instance = axios.create(httpConfig)
  14. /** 添加请求拦截器 **/
  15. instance.interceptors.request.use(config => {
  16. /**
  17. * 在这里:可以根据业务需求可以在发送请求之前做些什么。
  18. * config.headers['token'] = sessionStorage.getItem('token') || ''
  19. */
  20. // 执行请求脚本
  21. // https://mock.presstime.cn/mock/64bf8a00ce1b0ea640809069/test_copy_copy_copy/httpData?token=123&ss=ss
  22. const req = { ...config, urlKey: {} }
  23. eval(newCustomConfig.requestScript)
  24. for (const key in req.urlKey) {
  25. newCustomConfig.url = replaceUrlParam(newCustomConfig.url, key, req.urlKey[key])
  26. }
  27. config = { ...config, ...req, url: newCustomConfig.url }
  28. return config
  29. }, error => {
  30. // 对请求错误做些什么
  31. return Promise.reject(error)
  32. })
  33. /** 添加响应拦截器 **/
  34. instance.interceptors.response.use(response => {
  35. if (response.data.code === 200) {
  36. // 执行响应脚本
  37. const resp = _.cloneDeep(response.data)
  38. eval(newCustomConfig.responseScript)
  39. Message({
  40. message: '执行成功',
  41. type: 'success'
  42. })
  43. return Promise.resolve(resp)
  44. } else {
  45. Message({
  46. message: response.data.message,
  47. type: 'error'
  48. })
  49. return Promise.reject(response.data.message)
  50. }
  51. })
  52. const body = {}
  53. const pattern = /(body\.\w+)=(\w+)/g
  54. const replacement = "$1='$2'"
  55. newCustomConfig.body = newCustomConfig.body.replace(pattern, replacement)
  56. eval(newCustomConfig.body)
  57. return new Promise((resolve, reject) => {
  58. instance({
  59. method: newCustomConfig.method,
  60. url: newCustomConfig.url,
  61. params: newCustomConfig.params,
  62. data: newCustomConfig.method === 'post' ? body : undefined
  63. }).then(response => {
  64. resolve(response)
  65. }).catch(error => {
  66. reject(error)
  67. })
  68. })
  69. }
  70. // 动态替换url后面参数的值
  71. function replaceUrlParam (url, paramName, paramValue) {
  72. const regex = new RegExp(`([?&])${paramName}=.*?(&|$)`, 'i')
  73. const separator = url.indexOf('?') !== -1 ? '&' : '?'
  74. if (url.match(regex)) {
  75. return url.replace(regex, `$1${paramName}=${paramValue}$2`)
  76. } else {
  77. return `${url}${separator}${paramName}=${paramValue}`
  78. }
  79. }
  80. // 将参数的值替换掉其他配置中对应属性的值
  81. function replaceParams (customConfig) {
  82. let newConfig = _.cloneDeep(customConfig)
  83. newConfig.url = evalStrFunc(newConfig.paramsList, newConfig.url)
  84. newConfig.headers = evalArrFunc(newConfig.paramsList, newConfig.headers)
  85. newConfig.params = evalArrFunc(newConfig.paramsList, newConfig.params)
  86. newConfig.body = evalStrFunc(newConfig.paramsList, newConfig.body)
  87. return newConfig
  88. }
  89. function evalStrFunc (paramsList, string) {
  90. // 取name作为变量名, value作为变量值 { name: '站三', token: '123'}
  91. const params = paramsList.reduce((acc, cur) => {
  92. acc[cur.name] = cur.value
  93. return acc
  94. }, {})
  95. // 将url中 ${xxx} 替换成 ${params.xxx}
  96. const str = string.replace(/\$\{(\w+)\}/g, (match, p1) => {
  97. return '${params.' + p1 + '}'
  98. })
  99. const transformStr = ''
  100. // 将字符串中的${}替换为变量, 使用eval执行
  101. eval('transformStr = `' + str + '`')
  102. return transformStr
  103. }
  104. function evalArrFunc (paramsList, arr) {
  105. // 取name作为变量名, value作为变量值 { name: '站三', token: '123'}
  106. const params = paramsList.reduce((acc, cur) => {
  107. acc[cur.name] = cur.value
  108. return acc
  109. }, {})
  110. // 取name作为变量名, value作为变量值 { _name: '${name}', _token: '${token}'}
  111. const paramsListObj = arr.reduce((acc, cur) => {
  112. acc[cur.key] = cur.value
  113. return acc
  114. }, {})
  115. // 转成字符串
  116. const paramsListStr = JSON.stringify(paramsListObj)
  117. // 将url中 ${xxx} 替换成 ${params.xxx}
  118. const str = paramsListStr.replace(/\$\{(\w+)\}/g, (match, p1) => {
  119. return '${params.' + p1 + '}'
  120. })
  121. const transformStr = ''
  122. // 将字符串中的${}替换为变量, 使用eval执行
  123. eval('transformStr = `' + str + '`')
  124. const obj = JSON.parse(transformStr)
  125. return obj
  126. }