453 lines
14 KiB
Plaintext
453 lines
14 KiB
Plaintext
import { AkReqUploadOptions, AkReqOptions, AkReqResponse, AkReqError } from './interface.uts';
|
||
import { SUPA_URL, SUPA_KEY, IS_TEST_MODE } from '@/ak/config.uts';
|
||
|
||
// token 持久化 key
|
||
const ACCESS_TOKEN_KEY = 'akreq_access_token';
|
||
const REFRESH_TOKEN_KEY = 'akreq_refresh_token';
|
||
const EXPIRES_AT_KEY = 'akreq_expires_at';
|
||
|
||
// 优化:用静态变量缓存 token,只有 set/clear 时同步 storage
|
||
|
||
// Web 端(H5)由于多账号联调需要,开启单 Tab 隔离的储流(sessionStorage)
|
||
function setAuthStore(key : string, value : any) {
|
||
// #ifdef H5
|
||
sessionStorage.setItem(key, String(value));
|
||
return;
|
||
// #endif
|
||
uni.setStorageSync(key, value);
|
||
}
|
||
function getAuthStore(key : string) : any | null {
|
||
// #ifdef H5
|
||
return sessionStorage.getItem(key);
|
||
// #endif
|
||
return uni.getStorageSync(key);
|
||
}
|
||
function removeAuthStore(key : string) {
|
||
// #ifdef H5
|
||
sessionStorage.removeItem(key);
|
||
return;
|
||
// #endif
|
||
uni.removeStorageSync(key);
|
||
}
|
||
|
||
let _accessToken : string | null = null;
|
||
let _refreshToken : string | null = null;
|
||
let _expiresAt : number | null = null;
|
||
|
||
export class AkReq {
|
||
static setToken(token : string, refreshToken : string, expiresAt : number) {
|
||
_accessToken = token;
|
||
_refreshToken = refreshToken;
|
||
_expiresAt = expiresAt;
|
||
setAuthStore(ACCESS_TOKEN_KEY, token);
|
||
setAuthStore(REFRESH_TOKEN_KEY, refreshToken);
|
||
setAuthStore(EXPIRES_AT_KEY, expiresAt);
|
||
}
|
||
static getToken() : string | null {
|
||
if (_accessToken != null) return _accessToken;
|
||
const t = getAuthStore(ACCESS_TOKEN_KEY) as string | null;
|
||
_accessToken = t;
|
||
return t;
|
||
}
|
||
static getRefreshToken() : string | null {
|
||
if (_refreshToken != null) return _refreshToken;
|
||
const t = getAuthStore(REFRESH_TOKEN_KEY) as string | null;
|
||
_refreshToken = t;
|
||
return t;
|
||
} static getExpiresAt() : number | null {
|
||
const val = _expiresAt;
|
||
if (val != null) return val;
|
||
const t = getAuthStore(EXPIRES_AT_KEY) as number | null;
|
||
_expiresAt = t;
|
||
return t;
|
||
}
|
||
static clearToken() {
|
||
_accessToken = null;
|
||
_refreshToken = null;
|
||
_expiresAt = null;
|
||
removeAuthStore(ACCESS_TOKEN_KEY);
|
||
removeAuthStore(REFRESH_TOKEN_KEY);
|
||
removeAuthStore(EXPIRES_AT_KEY);
|
||
} // 判断 token 是否即将过期(提前5分钟刷新)
|
||
static isTokenExpiring() : boolean {
|
||
const expiresAt = this.getExpiresAt();
|
||
if (expiresAt === null || expiresAt == 0) {
|
||
return true;
|
||
}
|
||
const now = Math.floor(Date.now() / 1000);
|
||
return (expiresAt - now) < 300; // 提前5分钟刷新
|
||
}
|
||
|
||
// 自动刷新 token,返回 true=已刷新,false=未刷新
|
||
static async refreshTokenIfNeeded(apikey ?: string) : Promise<boolean> {
|
||
// 没有 access_token 直接返回,不刷新
|
||
const accessToken = this.getToken();
|
||
if (accessToken === null || accessToken === "") {
|
||
return false;
|
||
}
|
||
if (!this.isTokenExpiring()) {
|
||
return false;
|
||
}
|
||
const refreshToken = this.getRefreshToken();
|
||
if (refreshToken === null || refreshToken === "") {
|
||
this.clearToken();
|
||
return false;
|
||
}
|
||
// 构造 header,必须带 apikey
|
||
let headers = new UTSJSONObject();
|
||
if (apikey !== null && apikey !== "") {
|
||
headers.set('apikey', apikey)
|
||
}
|
||
const reqData = new UTSJSONObject()
|
||
reqData.set('refresh_token', refreshToken)
|
||
try {
|
||
const res = await this.request({
|
||
url: SUPA_URL + '/auth/v1/token?grant_type=refresh_token',
|
||
method: 'POST',
|
||
data: reqData,
|
||
headers: headers,
|
||
contentType: 'application/json'
|
||
}, true); // skipRefresh=true,避免递归
|
||
const data = res.data as UTSJSONObject | null;
|
||
let accessToken : string | null = null;
|
||
let refreshTokenNew : string | null = null;
|
||
let expiresAt : number | null = null;
|
||
if (data != null && typeof data.getString === 'function' && typeof data.getNumber === 'function') {
|
||
accessToken = data.getString('access_token');
|
||
refreshTokenNew = data.getString('refresh_token');
|
||
expiresAt = data.getNumber('expires_at');
|
||
}
|
||
if (accessToken !== null && refreshTokenNew !== null && expiresAt !== null) {
|
||
this.setToken(accessToken, refreshTokenNew, expiresAt);
|
||
return true;
|
||
} else { this.clearToken(); uni.$emit('AUTH_SESSION_EXPIRED', { reason: 'refresh_failed' }); return false; }
|
||
} catch (e) {
|
||
this.clearToken();
|
||
return false;
|
||
}
|
||
}
|
||
// options: AkReqOptions, skipRefresh: boolean = false
|
||
static async request(options : AkReqOptions, skipRefresh ?: boolean) : Promise<AkReqResponse<any>> {
|
||
// 自动刷新 token
|
||
if (skipRefresh != true) {
|
||
let apikey : string | null = null;
|
||
const headersObj = options.headers;
|
||
if (headersObj != null && typeof headersObj.getString === 'function') {
|
||
apikey = headersObj.getString('apikey');
|
||
}
|
||
await this.refreshTokenIfNeeded(apikey);
|
||
}
|
||
|
||
// 构建新的 headers 对象,确保所有字段都被正确传递
|
||
const newHeaders = new UTSJSONObject()
|
||
|
||
// 首先复制原始 headers
|
||
if (options.headers != null) {
|
||
const originalHeaders = options.headers
|
||
if (typeof originalHeaders.getString === 'function') {
|
||
// 复制 apikey
|
||
const apikeyStr = originalHeaders.getString('apikey')
|
||
if (apikeyStr != null) {
|
||
newHeaders.set('apikey', apikeyStr)
|
||
}
|
||
// 复制 Content-Type
|
||
const contentType = originalHeaders.getString('Content-Type')
|
||
if (contentType != null) {
|
||
newHeaders.set('Content-Type', contentType)
|
||
}
|
||
// 复制 Prefer
|
||
const prefer = originalHeaders.getString('Prefer')
|
||
if (prefer != null) {
|
||
newHeaders.set('Prefer', prefer)
|
||
}
|
||
// 复制 Authorization(如果存在)
|
||
const auth = originalHeaders.getString('Authorization')
|
||
if (auth != null) {
|
||
newHeaders.set('Authorization', auth)
|
||
}
|
||
}
|
||
}
|
||
|
||
// 补齐 apikey (如果 headers 中没有,则直接使用 SUPA_KEY 补全)
|
||
if (newHeaders.getString('apikey') == null) {
|
||
if (SUPA_KEY != null && SUPA_KEY != "") {
|
||
newHeaders.set('apikey', SUPA_KEY)
|
||
}
|
||
}
|
||
|
||
// 添加/更新 Authorization
|
||
const token = this.getToken();
|
||
|
||
// 检查原始 headers 中是否存在 Authorization
|
||
let existAuth: string | null = null
|
||
if (options.headers != null) {
|
||
const originalHeaders = options.headers
|
||
if (typeof originalHeaders.getString === 'function') {
|
||
existAuth = originalHeaders.getString('Authorization')
|
||
if (existAuth == null) {
|
||
existAuth = originalHeaders.getString('authorization')
|
||
}
|
||
}
|
||
}
|
||
|
||
if ((token != null && token != "") && (existAuth == null)) {
|
||
newHeaders.set('Authorization', `Bearer ${token}`)
|
||
}
|
||
|
||
// 确保 Content-Type 存在
|
||
if (newHeaders.getString('Content-Type') == null) {
|
||
const contentType = options.contentType ?? 'application/json'
|
||
if (contentType != null && contentType != "") {
|
||
newHeaders.set('Content-Type', contentType)
|
||
}
|
||
}
|
||
|
||
// 添加 Accept
|
||
newHeaders.set('Accept', 'application/json')
|
||
|
||
console.log('[AkReq.request] headers:', JSON.stringify(newHeaders))
|
||
|
||
const currentHeaders = newHeaders
|
||
|
||
const timeout = options.timeout ?? 10000;
|
||
const maxRetry = Math.max(0, options.retryCount ?? 0);
|
||
const baseDelay = Math.max(0, options.retryDelayMs ?? 300);
|
||
|
||
const doOnce = (): Promise<AkReqResponse<any>> => {
|
||
return new Promise<AkReqResponse<any>>((resolve) => {
|
||
uni.request({
|
||
url: options.url,
|
||
method: options.method ?? 'GET',
|
||
data: options.data,
|
||
header: currentHeaders,
|
||
timeout: timeout,
|
||
success: (res) => {
|
||
// HEAD 请求特殊处理:没有响应体,只有 headers
|
||
if (options.method == 'HEAD') {
|
||
const result = AkReq.createResponse<any>(
|
||
res.statusCode,
|
||
[] as Array<any>,
|
||
res.header as UTSJSONObject
|
||
);
|
||
resolve(result);
|
||
return;
|
||
}
|
||
|
||
// 兼容 res.data 可能为 string 或 UTSJSONObject 或 UTSArray
|
||
let data : UTSJSONObject | Array<UTSJSONObject> | null;
|
||
if (typeof res.data == 'string') {
|
||
const strData = res.data as string;
|
||
if (strData.length > 0 && /[^\s]/.test(strData)) {
|
||
try {
|
||
data = JSON.parse(strData) as UTSJSONObject;
|
||
} catch (e) {
|
||
// 非 JSON 响应(例如纯文本/空响应/数字等),保持原始字符串,避免 JSON.parse 崩溃
|
||
data = new UTSJSONObject({ raw: strData });
|
||
}
|
||
} else {
|
||
data = null;
|
||
}
|
||
} else if (Array.isArray(res.data)) {
|
||
data = res.data as UTSJSONObject[];
|
||
} else {
|
||
const objData = res.data as UTSJSONObject | null;
|
||
data = objData;
|
||
if (objData != null) {
|
||
const accessToken = objData.getString('access_token');
|
||
const refreshTokenNew = objData.getString('refresh_token');
|
||
const expiresAt = objData.getNumber('expires_at');
|
||
if (accessToken !== null && refreshTokenNew !== null && expiresAt !== null) {
|
||
AkReq.setToken(accessToken, refreshTokenNew, expiresAt);
|
||
}
|
||
}
|
||
}
|
||
const result = AkReq.createResponse<any>(
|
||
res.statusCode,
|
||
data ?? {},
|
||
res.header as UTSJSONObject
|
||
);
|
||
resolve(result);
|
||
},
|
||
fail: (err) => {
|
||
const errStatus = (err.errCode != null && typeof err.errCode === 'number') ? err.errCode : 0;
|
||
const result = AkReq.createResponse<any>(
|
||
errStatus,
|
||
{} as UTSJSONObject,
|
||
{} as UTSJSONObject,
|
||
new UniError('uni-request', errStatus, err.errMsg ?? 'request fail')
|
||
);
|
||
resolve(result);
|
||
}
|
||
});
|
||
});
|
||
};
|
||
|
||
let attempt = 0;
|
||
let lastRes: AkReqResponse<any> | null = null;
|
||
while (attempt <= maxRetry) {
|
||
const res = await doOnce();
|
||
lastRes = res;
|
||
// 仅网络失败/超时(errCode 非 0 且 status 非 2xx/3xx)时重试
|
||
const status = res.status ?? 0;
|
||
const isOk = status >= 200 && status < 400;
|
||
if (isOk) return res;
|
||
if (attempt === maxRetry) break;
|
||
// 简单退避
|
||
const delay = baseDelay * Math.pow(2, attempt);
|
||
await new Promise<void>((r) => { setTimeout(() => { r(); }, delay); });
|
||
attempt++;
|
||
}
|
||
const finalRes = lastRes!!;
|
||
// 全局处理 401 未授权:在非 refresh 场景下,清理 token。
|
||
// 测试模式下不强制跳登录页,避免影响任意跳转调试。
|
||
if ((finalRes.status === 401) && (skipRefresh !== true)) {
|
||
uni.$emit('AUTH_SESSION_EXPIRED', { reason: '401' });
|
||
|
||
try {
|
||
this.clearToken();
|
||
uni.showToast({ title: '未授权或登录已过期,请重新登录', icon: 'none' });
|
||
} catch (e) {}
|
||
try {
|
||
// 动态读取配置,避免 ak-req 模块与业务工程强耦合
|
||
// const cfg = require('@/ak/config.uts') as any
|
||
// const isTest = cfg != null ? (cfg.IS_TEST_MODE === true) : false
|
||
const isTest = IS_TEST_MODE
|
||
// if (!isTest) {
|
||
// uni.reLaunch({ url: '/pages/user/login' });
|
||
// }
|
||
} catch (e) {
|
||
// try { uni.reLaunch({ url: '/pages/user/login' }); } catch (e2) {}
|
||
}
|
||
}
|
||
return finalRes;
|
||
}
|
||
|
||
// 新增 upload 方法,支持 uni.uploadFile,自动带 token/apikey
|
||
static async upload(options : AkReqUploadOptions) : Promise<AkReqResponse<any>> {
|
||
// 上传前尝试刷新 token(若即将过期)。优先从 options.headers 或 apikey 字段获取 apikey
|
||
let apikey: string | null = null;
|
||
const hdr = options.headers;
|
||
if (hdr != null && typeof hdr.getString === 'function') {
|
||
apikey = hdr.getString('apikey');
|
||
}
|
||
if (apikey == null && options.apikey != null) apikey = options.apikey;
|
||
await this.refreshTokenIfNeeded(apikey != null ? apikey : null);
|
||
|
||
let headers = options.headers ?? ({} as UTSJSONObject);
|
||
const token = this.getToken();
|
||
if (token != null && token !== "") {
|
||
headers = Object.assign({}, headers, { Authorization: `Bearer ${token}` }) as UTSJSONObject;
|
||
}
|
||
if (apikey != null && apikey !== "") {
|
||
headers = Object.assign({}, headers, { apikey: apikey }) as UTSJSONObject;
|
||
}
|
||
// 默认 Accept
|
||
headers = Object.assign({ Accept: 'application/json' } as UTSJSONObject, headers) as UTSJSONObject;
|
||
|
||
const timeout = options.timeout ?? 10000;
|
||
const maxRetry = Math.max(0, options.retryCount ?? 0);
|
||
const baseDelay = Math.max(0, options.retryDelayMs ?? 300);
|
||
|
||
const doOnce = (): Promise<AkReqResponse<any>> => {
|
||
return new Promise<AkReqResponse<any>>((resolve) => {
|
||
const task = uni.uploadFile({
|
||
url: options.url,
|
||
filePath: options.filePath,
|
||
name: options.name,
|
||
formData: options.formData ?? {},
|
||
header: headers,
|
||
timeout: timeout,
|
||
success: (res : UploadFileSuccess) => {
|
||
let parsed: UTSJSONObject | null = null;
|
||
try {
|
||
parsed = JSON.parse(res.data) as UTSJSONObject;
|
||
} catch (e) {
|
||
parsed = null;
|
||
}
|
||
if (parsed != null) {
|
||
const accessToken = parsed.getString('access_token');
|
||
const refreshTokenNew = parsed.getString('refresh_token');
|
||
const expiresAt = parsed.getNumber('expires_at');
|
||
if (accessToken !== null && refreshTokenNew !== null && expiresAt !== null) {
|
||
AkReq.setToken(accessToken, refreshTokenNew, expiresAt);
|
||
}
|
||
}
|
||
const result = AkReq.createResponse<any>(
|
||
res.statusCode,
|
||
parsed ?? {},
|
||
headers
|
||
);
|
||
resolve(result);
|
||
},
|
||
fail: (err) => {
|
||
const errStatus = (err.errCode != null && typeof err.errCode === 'number') ? err.errCode : 0;
|
||
const result = AkReq.createResponse<any>(
|
||
errStatus,
|
||
{} as UTSJSONObject,
|
||
{} as UTSJSONObject,
|
||
new UniError('uni-upload', errStatus, err.errMsg ?? 'upload fail')
|
||
);
|
||
resolve(result);
|
||
}
|
||
});
|
||
if (options.onProgress != null && task != null) {
|
||
const progressCallback = (res: OnProgressUpdateResult) => {
|
||
const percent = res.progress as number; // 0-100
|
||
const sent = res.totalBytesSent as number | null;
|
||
const expected = res.totalBytesExpectedToSend as number | null;
|
||
if (options.onProgress != null) {
|
||
options.onProgress(percent, sent, expected);
|
||
}
|
||
};
|
||
task.onProgressUpdate(progressCallback);
|
||
}
|
||
});
|
||
};
|
||
|
||
let attempt = 0;
|
||
let lastRes: AkReqResponse<any> | null = null;
|
||
while (attempt <= maxRetry) {
|
||
const res = await doOnce();
|
||
lastRes = res;
|
||
const status = res.status ?? 0;
|
||
const isOk = status >= 200 && status < 400;
|
||
if (isOk) return res;
|
||
if (attempt === maxRetry) break;
|
||
const delay = baseDelay * Math.pow(2, attempt);
|
||
await new Promise<void>((resolve) => {
|
||
setTimeout(() => {
|
||
resolve();
|
||
}, delay);
|
||
});
|
||
attempt++;
|
||
}
|
||
return lastRes!!;
|
||
}
|
||
// 辅助方法:创建 AkReqResponse 对象,避免类型推断问题
|
||
static createResponse<T>(
|
||
status: number,
|
||
data: T | Array<T> ,
|
||
headers: UTSJSONObject,
|
||
error: UniError | null = null,
|
||
total: number | null = null,
|
||
page: number | null = null,
|
||
limit: number | null = null,
|
||
hasmore: boolean | null = null,
|
||
origin: any | null = null
|
||
): AkReqResponse<T> {
|
||
return {
|
||
status,
|
||
data,
|
||
headers,
|
||
error,
|
||
total,
|
||
page,
|
||
limit,
|
||
hasmore,
|
||
origin
|
||
};
|
||
}
|
||
|
||
}
|
||
|
||
export default AkReq; |