v-fetch.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import { mergeDeep } from "@vci/helper/src/object";
  2. const VfGlobalOption = {
  3. rootApi: "",
  4. method: "GET",
  5. headers: {},
  6. mode: "cors",
  7. credentials: "omit",
  8. serializeData: false,
  9. on: {
  10. beforeInit: null,
  11. beforeRequest: null,
  12. afterRequest: null,
  13. resolveData: null,
  14. failResolveData: null,
  15. error: null
  16. }
  17. };
  18. const vfs = [];
  19. const IgnoreNotificationMessages = [
  20. "the user aborted a request.",
  21. "signal is aborted without reason",
  22. "vm is destroyed",
  23. "refresh be killed by next",
  24. "is aborts"
  25. ];
  26. // v-fetch
  27. class Vf {
  28. constructor(option) {
  29. this.option = mergeDeep({
  30. cache: "default",
  31. headers: {},
  32. data: {},
  33. method: null,
  34. url: null,
  35. mode: null,
  36. credentials: null,
  37. dataType: "json",
  38. on: {
  39. abort: null
  40. },
  41. serializeData: null,
  42. isFormRequestData: false,
  43. withRootApi: true,
  44. enableResolveData: true,
  45. enableGlobalError: true
  46. }, option);
  47. this.init();
  48. }
  49. static Config(globalOption) {
  50. return mergeDeep(VfGlobalOption, globalOption);
  51. }
  52. static abortAllVfs() {
  53. vfs.forEach(vf => vf.abort());
  54. }
  55. init() {
  56. VfGlobalOption.on.beforeInit && VfGlobalOption.on.beforeInit(this.option, this);
  57. const { method, headers, cache, on, data, isFormRequestData, mode, credentials, serializeData } = this.option;
  58. this.ac = new AbortController();
  59. this.ac.signal.addEventListener("abort", () => on.abort && on.abort(this));
  60. this.isGetRequest = (method || VfGlobalOption.method) === "GET";
  61. try {
  62. this.url = this.generateUrl();
  63. this.request = new Request(this.url, {
  64. cache,
  65. method: method || VfGlobalOption.method,
  66. headers: {
  67. ...VfGlobalOption.headers,
  68. ...headers
  69. },
  70. mode: mode || VfGlobalOption.mode,
  71. credentials: credentials || VfGlobalOption.credentials,
  72. body: (() => {
  73. if(!this.isGetRequest) {
  74. if(data instanceof FormData) return data;
  75. if(isFormRequestData) {
  76. const formData = new FormData();
  77. Object.keys(data).forEach(key => formData.append(key, data[key]));
  78. return formData;
  79. } else {
  80. const rs = serializeData === null ? VfGlobalOption.serializeData : serializeData;
  81. if(rs) return Object.keys(data).map(k => `${k}=${data[k]}`).join("&");
  82. else return JSON.stringify(data);
  83. }
  84. }
  85. })(),
  86. signal: this.ac.signal
  87. });
  88. vfs.push(this);
  89. } catch (e) {
  90. this.vfError = this.formatError(e);
  91. }
  92. }
  93. generateUrl() {
  94. const { url, data, withRootApi } = this.option;
  95. return (withRootApi ? VfGlobalOption.rootApi : "") + url + (this.isGetRequest ? ((url.includes("?") ? (Object.keys(data).length > 0 ? "&" : "") : (Object.keys(data).length > 0 ? "?" : "")) + Object.keys(data).map(k => `${k}=${data[k]}`).join("&")) : "");
  96. }
  97. fetch() {
  98. return new Promise((resolve, reject) => {
  99. const { dataType, enableResolveData } = this.option;
  100. if(this.vfError) {
  101. reject(this.vfError);
  102. this.removeFromVfs();
  103. } else {
  104. VfGlobalOption.on.beforeRequest && VfGlobalOption.on.beforeRequest(this.request, this);
  105. fetch(this.request)
  106. .then(response => {
  107. const afterResolve = data => {
  108. if(!VfGlobalOption.on.resolveData || !enableResolveData) resolve(data);
  109. else {
  110. try {
  111. resolve(VfGlobalOption.on.resolveData(data, this));
  112. } catch (e) {
  113. if(VfGlobalOption.on.failResolveData) {
  114. try {
  115. VfGlobalOption.on.failResolveData(this, resolve, data, reject, e, response);
  116. } catch (e) {
  117. reject(this.formatError(e, response));
  118. }
  119. } else reject(this.formatError(e, response));
  120. }
  121. }
  122. VfGlobalOption.on.afterRequest && VfGlobalOption.on.afterRequest(data, this);
  123. };
  124. if(dataType === "json") response.json().then(data => afterResolve(data)).catch(e => reject(this.formatError(e, response)));
  125. if(dataType === "arrayBuffer") response.arrayBuffer().then(data => afterResolve(data)).catch(e => reject(this.formatError(e, response)));
  126. if(dataType === "blob") response.blob().then(data => afterResolve(data)).catch(e => reject(this.formatError(e, response)));
  127. if(dataType === "text") response.text().then(data => afterResolve(data)).catch(e => reject(this.formatError(e, response)));
  128. })
  129. .catch(e => reject(this.formatError(e)))
  130. .finally(() => this.removeFromVfs());
  131. }
  132. });
  133. }
  134. abort() {
  135. this.ac.abort();
  136. }
  137. formatError(e, response) {
  138. const { enableGlobalError } = this.option;
  139. const error = {
  140. msg: typeof e === "string" ? (e || "服务异常,请稍后再试") : e.toString(),
  141. err: e,
  142. vf: this,
  143. response
  144. };
  145. error.msg.includes("Failed to fetch") && (error.msg = "网络异常,请检查网络连接");
  146. enableGlobalError && VfGlobalOption.on.error && VfGlobalOption.on.error(error, this);
  147. return error;
  148. }
  149. removeFromVfs() {
  150. const targetIndex = vfs.findIndex(vf => vf === this);
  151. targetIndex !== -1 && vfs.splice(targetIndex, 1);
  152. }
  153. }
  154. function vf() {
  155. const vfInstance = new Vf(...arguments);
  156. return {
  157. vfInstance,
  158. fetch: vfInstance.fetch()
  159. };
  160. }
  161. const PluginVf = {
  162. install: (Vue, option = {}) => {
  163. const { config, PluginNotification } = option;
  164. Vf.Config(mergeDeep({
  165. rootApi: window.rootApi,
  166. on: {
  167. resolveData(data) {
  168. if(data["code"] !== 200) throw new Error(data["msg"] || "服务异常");
  169. return data["data"];
  170. },
  171. error: (e, vf) => {
  172. console.error("服务异常, ", vf.url, e);
  173. PluginNotification && !IgnoreNotificationMessages.some(inm => e.msg.includes(inm)) && PluginNotification.error(e.msg);
  174. }
  175. }
  176. }, config && config({ IgnoreNotificationMessages })));
  177. Vue.prototype.$vf = vf;
  178. }
  179. };
  180. export {
  181. Vf,
  182. vf,
  183. PluginVf
  184. };