index.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. var __assign = (this && this.__assign) || function () {
  2. __assign = Object.assign || function(t) {
  3. for (var s, i = 1, n = arguments.length; i < n; i++) {
  4. s = arguments[i];
  5. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  6. t[p] = s[p];
  7. }
  8. return t;
  9. };
  10. return __assign.apply(this, arguments);
  11. };
  12. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  13. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  14. return new (P || (P = Promise))(function (resolve, reject) {
  15. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  16. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  17. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  18. step((generator = generator.apply(thisArg, _arguments || [])).next());
  19. });
  20. };
  21. var __generator = (this && this.__generator) || function (thisArg, body) {
  22. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  23. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  24. function verb(n) { return function (v) { return step([n, v]); }; }
  25. function step(op) {
  26. if (f) throw new TypeError("Generator is already executing.");
  27. while (_) try {
  28. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  29. if (y = 0, t) op = [op[0] & 2, t.value];
  30. switch (op[0]) {
  31. case 0: case 1: t = op; break;
  32. case 4: _.label++; return { value: op[1], done: false };
  33. case 5: _.label++; y = op[1]; op = [0]; continue;
  34. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  35. default:
  36. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  37. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  38. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  39. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  40. if (t[2]) _.ops.pop();
  41. _.trys.pop(); continue;
  42. }
  43. op = body.call(thisArg, _);
  44. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  45. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  46. }
  47. };
  48. import { RequestMethod } from "./model/RequestMethod";
  49. import { ResponseType } from "./model/ResponseType";
  50. import { LogLevel } from "../ILogger";
  51. import { TimeoutError, HttpError } from "../Errors";
  52. import { NullLogger } from "../Loggers";
  53. /**
  54. * 封装微信ajax请求工具
  55. * @author halo
  56. */
  57. var Request = /** @class */ (function () {
  58. /**
  59. * Creates an instance of Request.
  60. * 实例化配置
  61. * @param {*} [config]
  62. * @memberof Request
  63. */
  64. function Request(config, logger) {
  65. if (config === void 0) { config = {}; }
  66. // 写入配置
  67. if (wx) {
  68. // Time: 继承 signalR logger. 日志统一维护
  69. this.logger = logger ? logger : new NullLogger();
  70. }
  71. else {
  72. throw new Error("当前运行环境不是微信运行环境");
  73. }
  74. // custom wx request promise library.
  75. this.setConfig(config);
  76. }
  77. /**
  78. * merge config
  79. * @param config
  80. */
  81. Request.prototype.setConfig = function (config) {
  82. if (config === void 0) { config = {}; }
  83. // 合并默认配置和
  84. this.config = __assign({ baseUrl: "http://", headers: { "Content-Type": "application/json" }, forceEnableHttps: false, method: RequestMethod.GET, responseType: ResponseType.JSON, responseEncoding: "utf8", timeout: 60 * 1000, transformRequest: [], transformResponse: [] }, config);
  85. // 请求头默认附加response 解析器
  86. if (!this.config.transformResponse) {
  87. this.config.transformResponse = [];
  88. }
  89. this.logger.log(LogLevel.Information, "set config success.");
  90. };
  91. /**
  92. * 请求参数序列化
  93. *
  94. * @param {RequestOptions} options
  95. * @memberof Request
  96. *
  97. * @description 只支持普通get请求,和content-type = json 的 其他请求(post,put,delete,patch)
  98. */
  99. Request.prototype.handleRequestOptions = function (options) {
  100. return __awaiter(this, void 0, void 0, function () {
  101. var _i, _a, fun, e_1;
  102. return __generator(this, function (_b) {
  103. switch (_b.label) {
  104. case 0:
  105. // 请求地址处理,对于非<scene>:// 请求,附加baseUrl
  106. if (options.url && !/:\/\/.+?/.test(options.url)) {
  107. options.url = ((options.config ? options.config.baseUrl : "") + "/" + options.url).replace(/([^:])(\/\/)/g, "$1/");
  108. }
  109. this.logger.log(LogLevel.Trace, "checked request url");
  110. // https 处理
  111. if (options.config && options.config.forceEnableHttps) {
  112. options.url = options.url.replace(/http:/, "https:");
  113. this.logger.log(LogLevel.Trace, "execute fix [request.config.forceEnableHttps] " + options.url);
  114. }
  115. // header 合并
  116. options.headers = Object.assign({}, options.config ? options.config.headers : {}, options.headers);
  117. this.logger.log(LogLevel.Trace, "merge headers ", options.headers);
  118. // 移除微信封锁参数
  119. delete options.headers["Referer"];
  120. this.logger.log(LogLevel.Trace, "try delete headers Referer.");
  121. // 替换请求内的ResponseType
  122. options.responseType = options.responseType
  123. ? options.responseType
  124. : options.config
  125. ? options.config.responseType
  126. : ResponseType.TEXT;
  127. this.logger.log(LogLevel.Trace, "checked responseType [" + options.responseType + "]");
  128. if (!(options.config && options.config.transformRequest)) return [3 /*break*/, 6];
  129. this.logger.log(LogLevel.Trace, "execute transform request list. -result\n", options.config);
  130. _i = 0, _a = options.config.transformRequest;
  131. _b.label = 1;
  132. case 1:
  133. if (!(_i < _a.length)) return [3 /*break*/, 6];
  134. fun = _a[_i];
  135. _b.label = 2;
  136. case 2:
  137. _b.trys.push([2, 4, , 5]);
  138. return [4 /*yield*/, fun(options)];
  139. case 3:
  140. _b.sent();
  141. return [3 /*break*/, 5];
  142. case 4:
  143. e_1 = _b.sent();
  144. throw e_1;
  145. case 5:
  146. _i++;
  147. return [3 /*break*/, 1];
  148. case 6:
  149. // debug print handled request options
  150. this.logger.log(LogLevel.Debug, "handled request options \n", options);
  151. return [2 /*return*/];
  152. }
  153. });
  154. });
  155. };
  156. /**
  157. * 验证响应结果,执行回调
  158. *
  159. * @param {*} resolve
  160. * @param {*} reject
  161. * @param {*} response
  162. * @memberof Request
  163. */
  164. Request.prototype.handleResponse = function (response) {
  165. return __awaiter(this, void 0, void 0, function () {
  166. var _i, _a, fun, res_1;
  167. return __generator(this, function (_b) {
  168. switch (_b.label) {
  169. case 0:
  170. if (!(response.options.config &&
  171. response.options.config.responseType == "json" &&
  172. response.options.config.transformResponse)) return [3 /*break*/, 6];
  173. _i = 0, _a = response.options.config.transformResponse;
  174. _b.label = 1;
  175. case 1:
  176. if (!(_i < _a.length)) return [3 /*break*/, 6];
  177. fun = _a[_i];
  178. _b.label = 2;
  179. case 2:
  180. _b.trys.push([2, 4, , 5]);
  181. // handler response
  182. return [4 /*yield*/, fun(response)];
  183. case 3:
  184. // handler response
  185. _b.sent();
  186. return [3 /*break*/, 5];
  187. case 4:
  188. res_1 = _b.sent();
  189. this.logger.log(LogLevel.Trace, "execute transform request list. -result \n ", res_1);
  190. throw res_1;
  191. case 5:
  192. _i++;
  193. return [3 /*break*/, 1];
  194. case 6:
  195. // debug print handled response context
  196. this.logger.log(LogLevel.Debug, "handled response context \n", response);
  197. return [2 /*return*/, Promise.resolve(response)];
  198. }
  199. });
  200. });
  201. };
  202. /**
  203. * 执行请求
  204. *
  205. * @param {RequestOptions} [options={
  206. * url: this.config.baseUrl
  207. * }]
  208. * @returns {Promise<any>}
  209. * @memberof Request
  210. */
  211. Request.prototype.executeRequest = function (options) {
  212. var _this = this;
  213. return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
  214. var error_1, task;
  215. var _this = this;
  216. return __generator(this, function (_a) {
  217. switch (_a.label) {
  218. case 0:
  219. this.logger.log(LogLevel.Trace, "execute request -options \n", options);
  220. // 合并 baseConfig
  221. options.config = options.config ? __assign(__assign({}, this.config), options.config) : __assign({}, this.config);
  222. if (this.checkAbout(options.config, reject))
  223. return [2 /*return*/];
  224. _a.label = 1;
  225. case 1:
  226. _a.trys.push([1, 3, , 4]);
  227. // 序列化请求参数
  228. return [4 /*yield*/, this.handleRequestOptions(options)];
  229. case 2:
  230. // 序列化请求参数
  231. _a.sent();
  232. return [3 /*break*/, 4];
  233. case 3:
  234. error_1 = _a.sent();
  235. // 抛出异常.
  236. return [2 /*return*/, reject(__assign({ data: null, header: null, statusCode: -1, options: options }, error_1))];
  237. case 4:
  238. if (this.checkAbout(options.config, reject))
  239. return [2 /*return*/];
  240. // print fixed options
  241. this.logger.log(LogLevel.Debug, "fixed options \n", options);
  242. // execute request
  243. this.logger.log(LogLevel.Trace, "invoke wx.request");
  244. task = wx.request({
  245. url: options.url,
  246. data: options.data,
  247. dataType: options.responseType,
  248. header: options.headers,
  249. method: options.method,
  250. responseType: (function () {
  251. switch (options.responseType) {
  252. case "json":
  253. case "text":
  254. return "text";
  255. case "arraybuffer":
  256. return "arraybuffer";
  257. }
  258. })(),
  259. success: function (res) { return __awaiter(_this, void 0, void 0, function () {
  260. var data, header, statusCode, errMsg, responseOptions;
  261. var _this = this;
  262. return __generator(this, function (_a) {
  263. if (this.checkAbout(options.config, reject))
  264. return [2 /*return*/];
  265. this.logger.log(LogLevel.Debug, "origin response context \n", res);
  266. data = res.data, header = res.header, statusCode = res.statusCode, errMsg = res.errMsg;
  267. responseOptions = {
  268. data: data,
  269. header: header,
  270. statusCode: statusCode,
  271. options: options,
  272. errMsg: errMsg
  273. };
  274. // 调用响应处理链(并返回结果)
  275. this.handleResponse(responseOptions)
  276. .then(function (res) {
  277. // print debug
  278. _this.logger.log(LogLevel.Debug, "handle response context is success. \n", res);
  279. /**
  280. * check and cache cookie (if has) |
  281. * @description 这里因为 signalR的原因,内置了一个 cookies.js [library](https://github.com/jshttp/cookie/index.js)
  282. * 略有改写,暂时将cookie 扔到内存中维护(毕竟就signalr使用,不考虑扔到 localStore 中占地方).
  283. */
  284. if (options.config.cookie)
  285. options.config.cookie.set(options.url, header);
  286. // callback
  287. resolve(res);
  288. })
  289. .catch(function (res) {
  290. // print log
  291. _this.logger.log(LogLevel.Error, "handle response context is fail. \n ", res);
  292. // ! 这里为了兼容 signalR的错误格式,抛出继承了HttpError异常.
  293. var httpError = new HttpError(res.errMsg, res.statusCode);
  294. // callback - 合并后,返回,可以被认定为 继承 HttpError对象.
  295. reject(__assign(__assign({}, res), httpError));
  296. });
  297. return [2 /*return*/];
  298. });
  299. }); },
  300. fail: function (res) {
  301. var responseOptions = null;
  302. if (res && /request:fail socket time out timeout/.test(res.errMsg)) {
  303. // ! 这里为了兼容 signalR的错误格式,抛出继承了TimeoutError异常.
  304. responseOptions = __assign({ data: null, status: -1, errMsg: res.errMsg }, new TimeoutError(res.errMsg));
  305. }
  306. else {
  307. // ! 这里为了兼容 signalR的错误格式,抛出继承了HttpError异常.
  308. responseOptions = __assign({ data: null, status: -1, errMsg: res.errMsg }, new HttpError(res.errMsg, 500));
  309. }
  310. /**
  311. * @date 2019年12月11日 13:14:25
  312. * ! 修复bug,wx.request fail 情况下, 未调用 response 处理链.
  313. */
  314. // 调用响应处理链(并返回结果)
  315. _this.handleResponse(responseOptions)
  316. .then(function (res) {
  317. // print debug
  318. _this.logger.log(LogLevel.Debug, "handle response context is success. \n", res);
  319. /**
  320. * check and cache cookie (if has) |
  321. * @description 这里因为 signalR的原因,内置了一个 cookies.js [library](https://github.com/jshttp/cookie/index.js)
  322. * 略有改写,暂时将cookie 扔到内存中维护(毕竟就signalr使用,不考虑扔到 localStore 中占地方).
  323. */
  324. if (options.config.cookie)
  325. options.config.cookie.set(options.url, {});
  326. // callback
  327. resolve(res);
  328. })
  329. .catch(function (res) {
  330. // print log
  331. _this.logger.log(LogLevel.Error, "handle response context is fail. \n ", res);
  332. // ! 这里为了兼容 signalR的错误格式,抛出继承了HttpError异常.
  333. var httpError = new HttpError(res.errMsg, res.statusCode);
  334. // callback - 合并后,返回,可以被认定为 继承 HttpError对象.
  335. reject(__assign(__assign({}, res), httpError));
  336. });
  337. }
  338. });
  339. // 监听 headers 变化
  340. task.onHeadersReceived(function () {
  341. // 当检查到 about() 状态,中断请求
  342. if (_this.checkAbout(options.config, reject)) {
  343. // 中断请求
  344. task.abort();
  345. return;
  346. }
  347. });
  348. return [2 /*return*/];
  349. }
  350. });
  351. }); });
  352. };
  353. /**
  354. * 检查中断
  355. *
  356. * @memberof Request
  357. */
  358. Request.prototype.checkAbout = function (options, reject) {
  359. if (options.config && options.config.about) {
  360. reject({
  361. data: null,
  362. header: options.headers,
  363. statusCode: 412,
  364. options: options,
  365. errMsg: "网络异常" // 直接自定义错误了.
  366. });
  367. return true;
  368. }
  369. else {
  370. return false;
  371. }
  372. };
  373. /**
  374. * GET 请求
  375. * @description 封装调用
  376. * @param url 请求地址
  377. * @param data 请求参数
  378. * @param options 请求配置
  379. */
  380. Request.prototype.get = function (url, data, options) {
  381. if (data === void 0) { data = {}; }
  382. // print execute step
  383. this.logger.log(LogLevel.Trace, "invoke request.get()");
  384. // merge config
  385. var requestOptions = __assign(__assign({}, (function () { return (options ? options : {}); })()), { method: RequestMethod.GET, url: url,
  386. data: data });
  387. // execute and response
  388. return this.executeRequest(requestOptions);
  389. };
  390. /**
  391. * POST 请求
  392. * @description 封装调用
  393. * @param url 请求地址
  394. * @param data 请求参数
  395. * @param options 请求配置
  396. */
  397. Request.prototype.post = function (url, data, options) {
  398. if (data === void 0) { data = {}; }
  399. // print execute step
  400. this.logger.log(LogLevel.Trace, "invoke request.post()");
  401. // merge config
  402. var requestOptions = __assign(__assign({}, (function () { return (options ? options : {}); })()), { method: RequestMethod.POST, url: url,
  403. data: data });
  404. // execute and response
  405. return this.executeRequest(requestOptions);
  406. };
  407. /**
  408. * PUT 请求
  409. * @description 封装调用
  410. * @param url 请求地址
  411. * @param data 请求参数
  412. * @param options 请求配置
  413. */
  414. Request.prototype.put = function (url, data, options) {
  415. if (data === void 0) { data = {}; }
  416. // print execute step
  417. this.logger.log(LogLevel.Trace, "invoke request.put()");
  418. // merge config
  419. var requestOptions = __assign(__assign({}, (function () { return (options ? options : {}); })()), { method: RequestMethod.PUT, url: url,
  420. data: data });
  421. // execute and response
  422. return this.executeRequest(requestOptions);
  423. };
  424. /**
  425. * DELETE 请求
  426. * @description 封装调用
  427. * @param url 请求地址
  428. * @param data 请求参数
  429. * @param options 请求配置
  430. */
  431. Request.prototype.delete = function (url, data, options) {
  432. if (data === void 0) { data = {}; }
  433. // print execute step
  434. this.logger.log(LogLevel.Trace, "invoke request.delete()");
  435. // merge config
  436. var requestOptions = __assign(__assign({}, (function () { return (options ? options : {}); })()), { method: RequestMethod.DELETE, url: url,
  437. data: data });
  438. // execute and response
  439. return this.executeRequest(requestOptions);
  440. };
  441. /**
  442. * 多请求同步执行
  443. * @param taskQueue
  444. */
  445. Request.prototype.all = function (taskQueue) {
  446. // print execute step
  447. this.logger.log(LogLevel.Trace, "invoke request.all()");
  448. // merge config
  449. return Promise.all(taskQueue);
  450. };
  451. /**
  452. * 用于兼容 @aspnet/signalR 的 获取 cookie 方法
  453. *
  454. * @description 这里用内存对象来维护一个 在线 cookies
  455. * @param {string} url
  456. * @returns
  457. * @memberof Request
  458. */
  459. Request.prototype.getCookieString = function (url) {
  460. if (this.config && this.config.cookie) {
  461. return this.config.cookie.origin(url);
  462. }
  463. else {
  464. return "";
  465. }
  466. };
  467. Request.prototype.cookie = function (url, key) {
  468. if (this.config && this.config.cookie) {
  469. return this.config.cookie.get(url, key);
  470. }
  471. else {
  472. return "";
  473. }
  474. };
  475. return Request;
  476. }());
  477. export { Request };