Parcourir la source

cache部分http get

Michael Wang il y a 6 ans
Parent
commit
ebf3714df5
2 fichiers modifiés avec 26 ajouts et 0 suppressions
  1. 5 0
      src/utils/axios.js
  2. 21 0
      src/utils/axiosCache.js

+ 5 - 0
src/utils/axios.js

@@ -1,6 +1,7 @@
 import Vue from "vue";
 import axios from "axios";
 import { loadProgressBar } from "./axiosProgress";
+import cachingGet from "./axiosCache";
 import { Message } from "iview";
 import router from "../router";
 import { UPYUN_UPLOAD_URL, UPYUN_HEADER_AUTH } from "@/constants/constants.js";
@@ -87,6 +88,10 @@ qmInstance.defaults.withCredentials = true; //允许跨域携带cookie
 qmInstance.defaults.timeout = 10000; //超时时间
 qmInstance.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"; //标识这是一个 ajax 请求
 
+qmInstance.get = cachingGet(qmInstance.get, [
+  /\/api\/exam_question\/question\/\?question_id/,
+  /\/api\/ecs_exam_work\/exam\/\d+$/
+]);
 loadProgressBar(qmInstance);
 
 const upyunInstance = axios.create({

+ 21 - 0
src/utils/axiosCache.js

@@ -0,0 +1,21 @@
+export default function(get, regexes) {
+  // cachingGet
+  const cache = new Map();
+
+  return function cachedGet(url) {
+    const key = url;
+
+    if (regexes.some(regex => url.match(regex))) {
+      if (cache.has(key)) {
+        return cache.get(key);
+      } else {
+        const request = get(...arguments);
+        cache.set(key, request);
+        return request;
+      }
+    } else {
+      const request = get(...arguments);
+      return request;
+    }
+  };
+}