hookehuyr

refactor(auth): 优化授权逻辑并添加注释说明

添加详细注释解释 refreshSession 和 silentAuth 的返回值设计原因
使用 finally 确保 silentAuth 的 promise 锁正确释放
......@@ -133,9 +133,14 @@ export const refreshSession = async (options) => {
throw new Error('授权失败:没有获取到有效的会话信息')
}
// 写入本地缓存:后续请求会从缓存取 sessionid 并带到请求头
// NOTE: 写入本地缓存:后续请求会从缓存取 sessionid 并带到请求头
Taro.setStorageSync('sessionid', cookie)
/**
* refreshSession() 的返回值当前没有任何业务消费点:在 request.js 里只是 await refreshSession() ,不解构、不使用;其他地方也没直接调用它
* 所以 return { ...response.data, cookie } 目前属于“严谨保留”:方便未来需要拿 cookie / code / msg 做埋点、提示、分支处理时直接用(例如授权页显示更细错误、统计刷新成功率等)。
*/
return {
...response.data,
cookie,
......@@ -182,12 +187,33 @@ export const silentAuth = async (on_success, on_error, options) => {
try {
// 未有授权进行中时才发起一次授权,并复用 Promise
if (!auth_promise) {
auth_promise = do_silent_auth(show_loading).finally(() => {
auth_promise = null
})
/**
* 用 auth_promise 做“单例锁”,把同一时刻并发触发的多次授权合并成一次。
* 把正在执行的授权 Promise 存起来;后面如果又有人调用 silentAuth() ,
* 看到 auth_promise 不为空,就直接 await 同一个 Promise,避免同时发起多次 Taro.login / 换会话请求
* ---------------------------------------------------------------------------------------
* .finally(() => { auth_promise = null }) 不管授权成功还是失败(resolve/reject),都把“锁”释放掉。
* 不用 finally 的问题:如果授权失败抛错了,而你只在 .then 里清空,那么 auth_promise 会一直卡着旧的 rejected Promise;
* 后续再调用 silentAuth() 会复用这个失败的 Promise,导致永远失败、且永远不会重新发起授权。
* 用 finally :保证成功/失败都会清空,下一次调用才有机会重新走授权流程。
*/
auth_promise = do_silent_auth(show_loading)
.finally(() => {
auth_promise = null
})
}
const result = await auth_promise
if (on_success) on_success(result)
/**
* 当前返回值 没有实际消费点 :全项目只在 3 处调用,全部都 不使用返回值 。
* - 启动预加载: await silentAuth() 仅等待,不用结果, app.js
* - 授权页: silentAuth().then(() => returnToOriginalPage()) then 里也没接 res , auth/index.vue
* - 分享场景: await silentAuth(successCb, errorCb) 只看成功/失败分支,不用返回值, handleSharePageAuth
* 所以这行 return result 的作用目前是 语义完整 + 未来扩展位 :
* 如果以后要在调用处根据 code/msg/cookie 做分支或埋点,返回值就能直接用;现在等价于“只用 resolve/reject 表达成功失败”。
*/
return result
} catch (error) {
const error_msg = error?.message || '授权失败,请稍后重试'
......