request.js
6.63 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/**
* usedcar 请求层:@uj/api-core 的客户端工厂。
*
* 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器由 api-core 负责。
* public API 与旧壳一致:get/post/request(method, data, noSignAttr, requestPath, domainName, failTips)、
* getMock()、getApiFoxMock(),46 处调用点零改动。
*
* 与其它 app 的差异全部用语义化参数表达:
* · 路由前缀固定、凭据按 method 首段取 → defaultPath / resolveCredential
* · 成功也返回完整信封、非 20/21 一律 resolve → legacyEnvelope
* · 网络失败 / 超时提示改写 → beforeRequest / onTransportError
*/
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createClient } from '@uj/api-core'
import { sign, domain, path, secretKey } from './http.js'
import util from '~/utils/util.js'
import { envIndex } from '~/config'
const DEFAULT_CRED = {
appKey: '48e5e13229b82c1b4e6e8c96151f0637',
secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
}
const getNetworkType = () =>
new Promise((resolve) => {
wx.getNetworkType({ success: (res) => resolve(res.networkType) })
})
/** 客户端公共配置:两个实例只差「会话从哪来」。 */
const ropOptions = {
hosts: { dj: domain.dj, scrm: domain.scrm, merchant: domain.merchants, ai: domain.AI },
// 路由前缀固定(旧壳 path = /rop-dj-car-boutique/router);requestPath 可整体覆盖。
defaultPath: path.replace(/router$/, ''),
getProjectName: (m) => m.split('.api')[0].split('.')[0],
resolveCredential: (pn, ht) => secretKey[ht === 'merchant' ? 'merchants' : pn] ?? DEFAULT_CRED,
// 本 app 的签名实现(字节级对齐旧壳):直接传函数,工厂内部包成签名策略。
signature: sign,
// 语义化开关:成功也返回完整信封、非登出码一律 resolve(旧壳语义)。
legacyEnvelope: true,
response: { toastOnOtherCodes: ['-1'] },
// 网络不可用:reject + toast(旧壳语义),由调用方 catch。
beforeRequest: async () => {
const type = await getNetworkType()
if (type == 'none') throw new Error('网络异常')
},
// wx 层失败:识别超时并输出诊断日志、改写提示文案。
onTransportError: (error) => {
// 旧壳 fail 分支会先关掉业务方可能开着的 loading。
wx.hideLoading?.()
const errMsg = (error && error.errMsg) || String(error || '')
const isTimeout = /timeout/i.test(errMsg) || error?.errno === 5
let pageRoute = ''
try {
const pages = getCurrentPages()
pageRoute = pages[pages.length - 1]?.route || ''
} catch (e) {
pageRoute = ''
}
console.error('[request fail]', { errMsg, isTimeout, pageRoute }, error)
return { message: isTimeout ? '请求超时,请重试' : '系统异常' }
},
onLoginRequired: (_code, { resource }) => {
const thisPage = wx.$router.getPageInstance()
wx.hideLoading()
// 出问题时能一眼看到是哪个接口判了登录失效,省得去 Network 里翻
console.warn('[login required]', resource)
if (thisPage?.route != 'pages/wxLogin/wxLogin') {
// 第三参对齐旧壳(getApp().login(true, "", url)):登录页靠它识别
// 「启动页 loading 的埋点接口超时」,避免重复弹窗打断首屏。
getApp().login(true, '', resource ?? '')
}
},
}
// 常规请求:sessionId 可能正在换取(启动 / 登录后),等闸门放行再发。
const client = createClient({
kind: 'rop',
...ropOptions,
session: { sessionId: () => util.waitSessionId() },
})
// 换取会话本身的接口不能等闸门,否则自己把自己锁死。
const sessionFreeClient = createClient({
kind: 'rop',
...ropOptions,
session: { sessionId: () => util.getSessionId() || '' },
})
/** 产出 sessionId 的接口(登录 / 换票 / 选账号),不参与等待。 */
const SESSION_FREE_METHODS = new Set([
'dj.api.smartcarlife.sms.noSignIn.login',
'dj.api.smartcarlife.sms.login',
'dj.api.smartcarlife.sms.not.code.login',
'dj.api.smartcarlife.jscode.login',
// scrm-sso 用 wx.login 的 code 换 openId,本身不需要会话,登录前就要调
'scrm.api.sso.weapp.jscode.getOpenId',
'dj.api.smartcarlife.login.accountAndPwd',
'dj.api.smartcarlife.login.log.add',
'dj.api.smartcarlife.workWechat.listSelectAccount',
'dj.api.smartcarlife.workWechat.selectAccountLogin',
])
const pickClient = (method) => (SESSION_FREE_METHODS.has(method) ? sessionFreeClient : client)
// domainName -> hostType:merchants 映射到 merchant,其余小写(dj/scrm/ai)。
const toHostType = (domainName) => (domainName === 'merchants' ? 'merchant' : domainName.toLowerCase())
const call = (method, data = {}, noSignAttr = [], requestPath, domainName = 'dj', failTips = true) =>
pickClient(method).post(method, data, {
hostType: toHostType(domainName),
path: requestPath,
noSignAttr,
silent: !failTips,
// 旧壳:含 file 的上传请求 120s,其余 60s。门面默认已改成 60s,这里显式钉住两档。
timeout: noSignAttr?.includes('file') ? 120 * 1000 : 60 * 1000,
})
const api = {
get: (method, data, noSignAttr, requestPath, domainName, failTips) =>
call(method, data, noSignAttr, requestPath, domainName, failTips),
post: (method, data, noSignAttr, requestPath, domainName, failTips) =>
call(method, data, noSignAttr, requestPath, domainName, failTips),
request: (method, data, noSignAttr, requestPath, domainName, failTips) =>
call(method, data, noSignAttr, requestPath, domainName, failTips),
// 配置中心拉取,与 ROP 无关,原样保留。
getMock(configModule = 'dj-car-boutique-work-wechat-miniapp') {
const env = { 1: 'develop', 2: 'test', 3: 'production', 4: 'beta' }[envIndex]
const configUrl = `https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=${configModule}&env=${env}`
return new Promise((resolve) => {
wx.request({
url: configUrl, data: {}, method: 'GET', header: {},
dataType: 'json', responseType: 'text',
success(response) { resolve(response.data) },
})
})
},
// 本地 Apifox mock,与 ROP 无关,原样保留。
getApiFoxMock(method, params) {
return new Promise((resolve) => {
wx.request({
url: `http://127.0.0.1:4523/m1/7739320-7483460-default/rop-scrm-clue/router?method=${method}`,
data: params, method: 'post',
header: { 'content-type': 'application/x-www-form-urlencoded' },
dataType: 'json', responseType: 'text',
success(response) { resolve(response.data) },
})
})
},
}
export default api