request.js
3.16 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* @Descripttion: 定义一个Request类,用于封装请求高德地图API的方法
* @version: 1.0.0
* @Author: limin
* @Date: 2023-07-04 17:25:31
* @LastEditors: limin
* @LastEditTime: 2023-07-05 14:50:37
* @FilePath: \glsx-map-sdk\src\request.js
*/
import md5 from './lib/md5'
import qs from './lib/qs'
import { MAP_OPTIONS } from './constants'
import { isMiniprogram } from './helper'
class Request {
// 构造函数,接收key和secret作为参数,如果没有传入,则使用默认值
constructor(key = MAP_OPTIONS.KEY, secret = MAP_OPTIONS.SECRET) {
// 将key和secret赋值给实例属性
this.key = key
this.secret = secret
}
/**对参数进行排序:按参数名升序 */
setLocaleCompare (params) {
// 将key添加到参数对象中
params.ak = this.key
params.output = 'json'
return Object.fromEntries(Object.entries(params).sort(([a], [b]) => a.localeCompare(b)))
}
/**签名计算(sig) */
getSign (params) {
return md5(`${decodeURIComponent(qs.stringify(this.setLocaleCompare(params)))}${this.secret}`)
}
/**封装的GET方法 */
get (method, data) {
// 调用request方法,传入请求方式为GET,请求路径为method,请求数据为data
return this.request('GET', method, data)
}
/**封装的请求方法 */
async request (RequestMethods, method, data = {}) {
// 调用getSign方法,传入请求数据和请求路径,得到签名
const sig = this.getSign(data, method),
obj = {
...this.setLocaleCompare(data),
sig
}
if (isMiniprogram) {
wx.showNavigationBarLoading()
try {
return new Promise((resolve, reject) => {
wx.request({
url: `${MAP_OPTIONS.domain}${method}`,
data: obj,
method: RequestMethods,
header: {
'content-type': 'application/json'
},
success: ({ data }) => {
const { status, result } = data
if (0 === status) {
resolve(result ? result : data)
} else {
wx.showToast({
title: 'errMsg',
icon: 'error'
})
}
},
fail: reject
})
})
} catch (error) {
wx.hideLoading()
console.error(`接口异常:`, error)
wx.showToast({
title: '系统异常',
icon: 'error'
})
throw error
} finally {
wx.hideNavigationBarLoading()
}
} else {
// 如果不是小程序环境,则使用window.fetch方法发送请求,并传入完整的请求地址和请求方式
const params = []
Object.keys(obj).map(key => {
params.push(`${key}=${encodeURIComponent(obj[key])}`)
})
try {
const res = await window.fetch(`${MAP_OPTIONS.domain}${method}?${params.join('&')}`, {
method: RequestMethods
})
const data = await res.json()
if (data.status == '1') return data
else throw data.info
} catch (error) {
console.error(`接口异常:`, error)
throw error
}
}
}
}
export default Request