import {
|
request
|
} from './require.js'
|
import cacheUtil from './cache.js'
|
|
/**
|
* 制造请求action
|
* @param method 请求方法: get(默认), post, put等
|
* @param type mutation类型
|
* @param url 请求url
|
* @param defaultQuery 默认参数
|
* @param useCache 是否使用缓存
|
* @param resolve 回调函数(可处理数据)
|
* @returns function
|
*/
|
function makeAction({
|
method = 'get',
|
type,
|
url,
|
defaultQuery,
|
useCache,
|
config = {}
|
},
|
resolve
|
) {
|
/**
|
* @param query 请求上传数据
|
*/
|
return ({
|
commit
|
}, {
|
query,
|
isCommit = true
|
} = {}) => {
|
if (config.header && config.header['Content-Type'] !== 'multipart/form-data' && !Array.isArray(query)) {
|
query = {
|
...defaultQuery,
|
...query
|
}
|
}
|
|
// get参数特殊处理
|
if (method === 'get' || method === 'delete') {
|
query = {
|
params: query
|
}
|
}
|
|
// 使用缓存
|
const cacheKey = `${method}_${url}_${JSON.stringify(query)}`
|
if (useCache) {
|
const resData = cacheUtil.getParseItem(cacheKey)
|
if (resData) {
|
resolve && resolve(resData)
|
type && isCommit && commit(type, resData.data)
|
return Promise.resolve(resData)
|
}
|
}
|
// 请求
|
return request[method](url, query, config).then(
|
(resData = {}) => {
|
// 使用缓存
|
if (useCache) {
|
Object.keys(resData).length &&
|
cacheUtil.setParseItem(cacheKey, resData)
|
}
|
resolve && resolve(resData)
|
type && isCommit && commit(type, resData.data)
|
return Promise.resolve(resData)
|
}
|
)
|
}
|
}
|
|
export default makeAction
|