zhoudw
2022-01-10 07562200a704b8eaf9c1d080bf8bd12165a97647
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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