utils.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { queryString } from "@dage/utils";
  2. /**
  3. * 转换 Headers 为 对象形式
  4. * @param headers
  5. */
  6. export function headersToObject(headers) {
  7. return Array.from(headers.entries()).reduce((prev, cur) => {
  8. const [key, value] = cur;
  9. prev[key] = value;
  10. return prev;
  11. }, {});
  12. }
  13. /**
  14. * 能携带参数的请求方法
  15. * @param method
  16. */
  17. export function methodsHasBody(method) {
  18. return method !== "GET" && method !== "HEAD";
  19. }
  20. /**
  21. * 序列化载荷
  22. * @param headers
  23. * @param body
  24. */
  25. export function serializeBody(headers, body) {
  26. if (body == null) {
  27. return body;
  28. }
  29. if (isArrayBuffer(body) || isBlob(body) || isFormData(body)) {
  30. return body;
  31. }
  32. const contentType = headers["content-type"];
  33. if (contentType === "application/x-www-form-urlencoded") {
  34. // 序列化为查询字符串
  35. return queryString.stringify(body);
  36. }
  37. return JSON.stringify(body);
  38. }
  39. export function isFormData(value) {
  40. return typeof FormData !== "undefined" && value instanceof FormData;
  41. }
  42. export function isBlob(value) {
  43. return typeof Blob !== "undefined" && value instanceof Blob;
  44. }
  45. export function isArrayBuffer(value) {
  46. return typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer;
  47. }
  48. /**
  49. * 根据body生成对应的contentType
  50. * @param body http body
  51. */
  52. export function detectContentType(body) {
  53. if (body == null) {
  54. return null;
  55. }
  56. if (isFormData(body) || isArrayBuffer(body)) {
  57. return null;
  58. }
  59. if (isBlob(body)) {
  60. return body.type || null;
  61. }
  62. if (typeof body === "object" ||
  63. typeof body === "number" ||
  64. Array.isArray(body)) {
  65. return "application/json;charset=UTF-8";
  66. }
  67. return "application/x-www-form-urlencoded;charset=UTF-8";
  68. }
  69. export function getResponseType(config) {
  70. const meta = config.meta;
  71. return (meta === null || meta === void 0 ? void 0 : meta.responseType) || "json";
  72. }
  73. export function serializeResponseBody(res, config) {
  74. const responseType = getResponseType(config);
  75. switch (responseType) {
  76. case "arrayBuffer":
  77. return res.arrayBuffer().then((data) => ({ data }));
  78. case "blob":
  79. return res.blob().then((data) => ({ data }));
  80. case "json":
  81. return res.json();
  82. case "text":
  83. return res.text().then((data) => ({ data }));
  84. default:
  85. return Promise.reject(new Error("传入的meta.responseType 不符合规范"));
  86. }
  87. }