找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/core/http/HttpManager.ts
1import { frameworkManager } from "../base/FrameworkClassRegistry";
2import { Framework } from "../../Framework";
3import { IFrameworkManager } from "../base/IFrameworkManager";
4import { Singleton } from "../base/Singleton";
5import { HttpMethod, type HttpRawResult, type HttpRequestOptions } from "./HttpDefine";
6
7function isAbsoluteUrl(url: string): boolean {
8 return /^https?:\/\//i.test(url);
9}
10
11function buildQuery(data: Record<string, unknown>): string {
12 const parts: string[] = [];
13 for (const key of Object.keys(data)) {
14 const v = data[key];
15 if (v === undefined || v === null) {
16 continue;
17 }
18 if (typeof v === "object") {
19 parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(JSON.stringify(v))}`);
20 } else {
21 parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`);
22 }
23 }
24 if (parts.length === 0) {
25 return "";
26 }
27 return `?${parts.join("&")}`;
28}
29
30/**
31 * 通用 HTTP(基于 XMLHttpRequest)
32 */
33@frameworkManager()
34export class HttpManager extends Singleton<HttpManager> implements IFrameworkManager {
35 Name: string = "HttpManager";
36
37
38 public static serverAddress = "";
39
40 private static readonly requestMap: Map<string, number> = new Map();
41
42 public async Init(): Promise<void> {
43 // 记录管理器初始化入口,便于排查启动顺序。
44 Framework.Log.Log(this.Name, "Init", "初始化HTTP管理器");
45 }
46
47 public DeInit(): void {
48
49 }
50
51 Update(deltaTime: number): void {
52 }
53
54
55 /**
56 * 规范化请求方法:未传或非法字符串时默认 POST;仅接受 {@link HttpMethod} 枚举中的值。
57 */
58 private static normalizeMethod(options: HttpRequestOptions): HttpMethod {
59 const m = (options.method ?? HttpMethod.POST) as string;
60 return (Object.values(HttpMethod) as string[]).includes(m) ? (m as HttpMethod) : HttpMethod.POST;
61 }
62
63 /**
64 * 拼出最终请求 URL:
65 * - `url` 已是 http(s) 开头则原样为基准,否则前接 `host`(若有)或 {@link HttpManager.serverAddress};
66 * - GET 且 `data` 为普通对象时,序列化为查询串追加到 URL(若 URL 已有 `?` 则用 `&` 衔接)。
67 */
68 private static buildFullUrl(method: HttpMethod, options: HttpRequestOptions): string {
69 const path = options.url;
70 const base = options.host ?? HttpManager.serverAddress;
71 let full = isAbsoluteUrl(path) ? path : `${base}${path}`;
72 if (method === HttpMethod.GET && options.data != null && typeof options.data === "object" && !Array.isArray(options.data)) {
73 const q = buildQuery(options.data as Record<string, unknown>);
74 if (q) {
75 full += full.includes("?") ? `&${q.slice(1)}` : q;
76 }
77 }
78 return full;
79 }
80
81 /**
82 * 生成「防重复请求」用的唯一键:方法 + 完整 URL + 请求体指纹。
83 * GET 仅依赖 URL(查询串已含在 fullUrl);POST 等对 `data` 做字符串化后加入键,避免同 URL 不同 body 被误判为重复。
84 */
85 private static makeDedupeKey(method: HttpMethod, fullUrl: string, data: unknown): string {
86 const body =
87 method === HttpMethod.GET
88 ? ""
89 : typeof data === "string"
90 ? data
91 : JSON.stringify(data ?? {});
92 return `${method}\n${fullUrl}\n${body}`;
93 }
94
95 /**
96 * callback 风格请求
97 */
98 public static request(options: HttpRequestOptions): void {
99 const method = HttpManager.normalizeMethod(options);
100 const fullUrl = HttpManager.buildFullUrl(method, options);
101 const key = HttpManager.makeDedupeKey(method, fullUrl, options.data);
102
103 if (!options.enableMult && HttpManager.requestMap.has(key)) {
104 console.warn("HttpManager", "重复请求已忽略", key);
105 return;
106 }
107 if (!options.enableMult) {
108 HttpManager.requestMap.set(key, 1);
109 }
110
111 HttpManager.execute(method, fullUrl, options)
112 .then((res) => {
113 options.callback?.(res);
114 })
115 .catch((err: unknown) => {
116 console.warn("HttpManager request error", err);
117 options.callback?.({ statusCode: 0, data: null });
118 })
119 .finally(() => {
120 if (!options.enableMult) {
121 HttpManager.requestMap.delete(key);
122 }
123 });
124 }
125
126 /**
127 * Promise 风格请求
128 */
129 public static requestAsync(options: HttpRequestOptions): Promise<HttpRawResult> {
130 const method = HttpManager.normalizeMethod(options);
131 const fullUrl = HttpManager.buildFullUrl(method, options);
132 const key = HttpManager.makeDedupeKey(method, fullUrl, options.data);
133
134 if (!options.enableMult && HttpManager.requestMap.has(key)) {
135 console.warn("HttpManager", "重复请求", key);
136 return Promise.reject(new Error("duplicate_request"));
137 }
138 if (!options.enableMult) {
139 HttpManager.requestMap.set(key, 1);
140 }
141
142 return HttpManager.execute(method, fullUrl, options).finally(() => {
143 if (!options.enableMult) {
144 HttpManager.requestMap.delete(key);
145 }
146 });
147 }
148
149 private static execute(method: HttpMethod, fullUrl: string, options: HttpRequestOptions): Promise<HttpRawResult> {
150 return new Promise((resolve, reject) => {
151 const xhr = new XMLHttpRequest();
152 const timeoutMs = options.timeoutMs ?? 15000;
153 xhr.timeout = timeoutMs;
154
155 xhr.ontimeout = () => {
156 reject(new Error("http_timeout"));
157 };
158 xhr.onerror = () => {
159 reject(new Error("http_error"));
160 };
161 xhr.onreadystatechange = () => {
162 if (xhr.readyState !== 4) {
163 return;
164 }
165 const sc = xhr.status;
166 let data: unknown = null;
167 const text = xhr.responseText;
168 if (text) {
169 try {
170 data = JSON.parse(text);
171 } catch {
172 data = text;
173 }
174 }
175 resolve({ statusCode: sc, data });
176 };
177 xhr.open(method, fullUrl, true);
178
179 const headers = options.headers ?? {};
180 const hasContentType = Object.keys(headers).some((k) => k.toLowerCase() === "content-type");
181 if (!hasContentType && method !== HttpMethod.GET) {
182 xhr.setRequestHeader("Content-Type", "application/json");
183 }
184 for (const k of Object.keys(headers)) {
185 xhr.setRequestHeader(k, headers[k]!);
186 }
187
188 if (method === HttpMethod.GET) {
189 xhr.send();
190 } else {
191 const body = options.data;
192 xhr.send(typeof body === "string" ? body : JSON.stringify(body ?? {}));
193 }
194 });
195 }
196}
讲解197 行
通用 XHR HTTP 客户端人工通读

HttpManager.ts

基于 XMLHttpRequest 提供回调与 Promise 两种请求入口,统一规范化方法、拼接地址、序列化 GET 查询串、补默认请求头,并用一张静态表对同方法同地址同请求体的并发请求去重。它只负责传输,业务解析与重试由调用方处理。

按 normalizeMethod、buildFullUrl、makeDedupeKey、request、requestAsync、execute 的顺序读,重点看去重键的构造与 finally 里的删除。

特殊处理与易错点

7方法检查地址是否以HTTP或HTTPS协议开头,忽略协议字母大小写。
11方法跳过空值并编码各键值,对象转JSON后拼成带问号的查询串。
33注释通用 HTTP(基于 XMLHttpRequest)
34注释HttpManager:通用 HTTP(基于 XMLHttpRequest)
35属性管理器名称,日志里的模块标识。
42方法只写一条初始化日志,不创建 XHR 也不设置默认地址。
44注释记录管理器初始化入口,便于排查启动顺序。
47方法空实现,静态去重表与默认地址都不清理,跨会话复用。
51方法空实现,请求完全由 XHR 事件驱动,没有逐帧任务。
58方法取传入方法并对照枚举白名单,缺失或不在枚举内的一律按 POST 处理。
68方法绝对地址原样使用,否则拼 host 或默认地址;GET 的普通对象数据再序列化成查询串追加。
85方法把方法、完整地址和请求体指纹拼成去重键,GET 只依赖地址不看请求体。
98方法做去重检查后发起请求,成功或失败都回调,最后从去重表删除键。
129方法做去重检查后返回 Promise,成功时给统一结果,失败或重复时 reject。
149方法创建 XHR 并设置超时与三个事件回调,按方法决定请求头与请求体后发出。