This commit is contained in:
ky_sunl
2021-04-22 13:37:25 +00:00
parent 575a22954f
commit d1c9e5a71e
699 changed files with 1062425 additions and 40640 deletions

156
Web/src/common/api/index.js Normal file
View File

@@ -0,0 +1,156 @@
/**
* api
* v1.2
*/
import axios from 'axios'
import { token } from '@/common/token'
import status from './status'
import app from '@/main'
axios.defaults.baseURL = '/api'
/**
* 最终直接根据url名称调用接口方法
* 例如
* import { api } from '@/api'
* api.getItemGroupType(parmas).then(...)
*/
import urls from './requests'
const initInstance = (options) => {
const instance = axios
.create({
headers: {
Authorization: 'Bearer ' + token.value
},
...options
})
instance.interceptors.response.use((res) => {
if (res.data.status === status.Unauthorized) {
handlerUnauthorized()
}
return res
}, (err) => {
return Promise.reject(err)
})
return instance
}
const errerCodes = [status.BadRequest, status.InternalServerError]
const errorNotification = ({ code, message }) => {
switch (message.constructor) {
case Array:
message.map(p => {
app.$notification.error({
duration: 0,
message: p.field,
description: p.messages.join('/'),
})
})
break
default:
app.$notification.error({
duration: 0,
message: code || '错误',
description: message,
})
break
}
}
const handlerUnauthorized = () => {
token.value = ''
app.$router.replace({
path: '/login'
}).catch(() => { })
}
const api = {}
for (let key in urls) {
const item = urls[key]
let url = '',
method = 'post',
options = {}
if (item.constructor === String) {
url = item
} else if (item.constructor === Array) {
url = item[0]
if (item[1]) {
method = item[1].toLowerCase()
}
if(item[2]) {
options = item[2]
}
} else if (item.constructor === Object) {
url = item.url
if (item.method) {
method = item.method.toLowerCase()
}
}
api[`${key}Wait`] = function (params = {}) {
if (method === 'post') {
return initInstance(options).post(url, params)
} else {
return initInstance(options).get(url, {
params
})
}
}
api[key] = function (params = {}) {
return new Promise((reslove, reject) => {
api[`${key}Wait`](params)
.then((res) => {
const { data } = res
if (errerCodes.indexOf(data.code) >= 0) {
errorNotification(data)
reject([ArrayBuffer, Blob].indexOf(data.constructor) > -1 ? res : data)
} else if (data.code === status.Unauthorized) {
handlerUnauthorized()
} else {
reslove([ArrayBuffer, Blob].indexOf(data.constructor) > -1 ? res : data)
}
})
.catch(({ response: { data } }) => {
if (process.env.VUE_APP_NODE_ENV === 'development') {
errorNotification(data)
reject(data)
if (data.code === status.Unauthorized) {
handlerUnauthorized()
}
} else {
errorNotification({
message: '发生错误,请联系管理员'
})
}
})
})
}
api[key].prototype.name = key
}
/**
* 并发请求,与axios.all方式相同
* 但是使用的接口函数为this.$api.[接口名]E
*/
api.$queue = function (queue) {
return new Promise((reslove) => {
axios.all(queue).then((results) => {
const res = results.map(p => p.data)
reslove(res)
})
})
}
export {
axios,
api,
status
}