http.uts 6.75 KB
import { storage } from "../../utils/storage.uts";
import { djDomain, djSecretKey, domain, merchantDomain, pathEnum, secretKey } from "../env.uts";
import { sign } from "./sign.uts";

type HostType = "dj" | "ip" | "merchant" | "scrm";

const HOST: Record<HostType, string> = {
	scrm: domain,
	dj: djDomain,
	merchant: merchantDomain,
	ip: "http://192.168.1.125:8080"
};

/**
 * HTTP 请求封装(从 gl_tape/api/request/http.js 迁移)
 * - 统一处理 GET / POST
 * - 自动注入 appKey / secret / sessionId 等并完成参数签名
 * - 处理业务 code 及登录态失效跳转
 */
class Request {
	/**
	 * 业务方法调用封装
	 * @param method ROP 接口方法名
	 * @param data 业务参数
	 * @param returnAll 是否返回完整响应体
	 * @param hostType 域名类型
	 */
	fetch(method: string, data: UTSJSONObject, returnAll: boolean = true, hostType?: HostType): Promise<any> {
		const payload = {} as UTSJSONObject;
		// method
		payload.method = method;
		// 合并业务参数
		const dataKeys = Object.keys(data as any) as string[];
		for (const key of dataKeys) {
			// @ts-ignore
			payload[key] = (data as UTSJSONObject)[key];
		}
		return this.post(payload, returnAll, hostType);
	}

	get(params: UTSJSONObject, returnAll: boolean = false, hostType?: HostType): Promise<any> {
		return this.request("GET", params, returnAll, hostType);
	}

	post(params: UTSJSONObject, returnAll: boolean = false, hostType?: HostType, timeout?: number): Promise<any> {
		return this.request("POST", params, returnAll, hostType, timeout);
	}

	/**
	 * 简单的原始 uni.request 封装
	 */
	uni_request(options: {
		data?: UTSJSONObject;
		dataType?: string;
		header?: UTSJSONObject;
		method?: "GET" | "POST";
		responseType?: string;
		url: string;
	}): Promise<any> {
		return new Promise((resolve) => {
			uni.request({
				url: options.url,
				data: options.data ?? ({} as UTSJSONObject),
				method: options.method ?? "GET",
				header: options.header ?? ({} as UTSJSONObject),
				dataType: options.dataType ?? "json",
				responseType: options.responseType ?? "text",
				success: (response) => {
					resolve(response.data);
				}
			});
		});
	}

	/**
	 * 组装 ROP 请求参数并完成签名
	 */
	private getData(params: UTSJSONObject, hostType: HostType): UTSJSONObject {
		let projectName = (params.projectName ?? "") as string;

		if (projectName == "") {
			projectName = this.getRopProject(params.method as string);
		} else {
			// 使用后删除 projectName 字段
			delete params.projectName;
		}

		let appKey = "48e5e13229b82c1b4e6e8c96151f0637";
		let secret = "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b";

		const projectSecret = secretKey[projectName];
		if (projectSecret != null) {
			appKey = projectSecret.appKey;
			secret = projectSecret.secret;
		}

		if (hostType == "dj") {
			appKey = djSecretKey.appKey;
			secret = djSecretKey.secret;
		}

		const sessionId = storage.get("sessionId") as null | string;
		let noSignAttr: string[] = [];

		if (params.sessionId == null && sessionId != null && sessionId != "") {
			params.sessionId = sessionId;
		}

		if (params.delSessionId != null) {
			delete params.sessionId;
			delete params.delSessionId;
		}

		if (params.noSignAttr != null) {
			noSignAttr = params.noSignAttr as string[];
			delete params.noSignAttr;
		}

		params.v = "1.0.0";
		params.format = "json";
		params.locale = "zh_CN";
		params.source = "app";
		params.appKey = appKey;

		return sign(params, secret, noSignAttr);
	}

	/**
	 * 根据 method 解析出 rop 项目名
	 * @example sso.xxx.xxx => 第三个段作为项目名
	 */
	private getRopProject(method: string): string {
		const parts = method.split(".");
		if (parts.length >= 3) {
			return parts[2];
		}
		return "";
	}

	private request(
		requestMethod: "GET" | "POST",
		params: UTSJSONObject,
		returnAll: boolean,
		hostType: HostType | undefined,
		timeout?: number
	): Promise<any> {
		const finalHostType: HostType = hostType ?? "dj";

		return new Promise((resolve, reject) => {
			uni.getNetworkType({
				success: (res) => {
					if (res.networkType == "none") {
						uni.hideLoading();
						uni.showToast({
							title: "网络异常",
							icon: "none"
						});
						reject("网络异常");
						return;
					}

					const header =
						requestMethod == "POST"
							? {
								"content-type": "application/x-www-form-urlencoded"
							}
							: {
								"Cache-Control": "no-cache"
							};

					let projectName = (params.projectName ?? "") as string;
					if (projectName == "") {
						projectName = this.getRopProject(params.method as string);
					}

					const path = pathEnum[projectName] ?? "";
					const requestData = this.getData(params, finalHostType);

					uni.request({
						url: `${HOST[finalHostType]}${path}router?method=${requestData.method}`,
						data: requestData,
						method: requestMethod,
						header,
						dataType: "json",
						responseType: "text",
						timeout: timeout ?? 60_000,
						success: (response) => {
							const data: any = response.data;
							const statusCode = response.statusCode;

							if (data == null || statusCode != 200) {
								uni.hideLoading();
								let errMsg = "";
								if (data == null) {
									errMsg = "获取数据失败,请重试。";
								} else {
									errMsg = "服务器暂时不可用,请稍后再次尝试。";
								}
								reject(errMsg);
								return;
							}

							const code = (data.code ?? "") as number | string;
							const message = (data.message ?? "") as string;

							if (returnAll) {
								resolve(data);
								return;
							}

							if (code == 20 || code == 21) {
								const pages = getCurrentPages();
								const currentPage = pages[pages.length - 1];
								uni.hideLoading();
								if (currentPage.route != "pages/common/login") {
									uni.reLaunch({
										url: "/pages/common/login"
									});
								}
							} else {
								if (`${code}` == "0") {
									resolve(data.data);
								} else {
									uni.hideLoading();
									uni.showToast({
										title: message != "" ? message : "系统异常",
										icon: "none"
									});
								}
							}
						},
						fail: (error) => {
							uni.hideLoading();
							let title = "系统异常";
							if (typeof error === "string") {
								title = error;
							} else {
								// @ts-ignore
								const errMsg = (error as any).errMsg as null | string;
								if (errMsg != null && errMsg != "") {
									title = errMsg;
								} else {
									title = JSON.stringify(error);
								}
							}

							console.error(`${params.method} 接口异常:`, error);
							uni.showToast({
								title,
								icon: "error"
							});
							reject(error);
						},
						complete: () => {
							uni.stopPullDownRefresh();
						}
					});
				}
			});
		});
	}
}

export const request = new Request();