From 8ff8326589cc4a765f5d83d91ea15e3749d92b35 Mon Sep 17 00:00:00 2001
From: Zamil Majdy <z.majdy1996@gmail.com>
Date: Wed, 22 Mar 2017 00:24:22 +0700
Subject: [PATCH] [#140382397] #6 Add caching mechanism on Server.jsx library

---
 assets/js/lib/server.jsx | 25 ++++++++++++++++---------
 package.json             |  2 +-
 2 files changed, 17 insertions(+), 10 deletions(-)

diff --git a/assets/js/lib/server.jsx b/assets/js/lib/server.jsx
index c87c2c0f..437a8637 100755
--- a/assets/js/lib/server.jsx
+++ b/assets/js/lib/server.jsx
@@ -1,4 +1,5 @@
-import Logger from './logger';
+import Logger from "./logger";
+import Storage from "./storage";
 
 export default class Server {
     static getCookie(name) {
@@ -17,7 +18,7 @@ export default class Server {
         return cookieValue;
     }
 
-    static _request(path, method, data) {
+    static _request(path, method, data, useCache = false) {
 
         let url = "/api" + path;
         let csrftoken = this.getCookie("csrftoken");
@@ -34,24 +35,30 @@ export default class Server {
         };
 
         let request = fetch(url, requestData);
-        return request.then((response) => {
+        let promise = request.then((response) => {
             // Logger.log("[Server] Calling", url, response);
             if (response.status < 200 || response.status > 399) {
-                Logger.log(response);
                 throw response;
             }
             if (response.status === 204) {
                 return response;
             }
             return response.json();
-        }).then((response) => {
-            // Logger.log("[Server] Response from", url, response);
-            return response;
         });
+
+        return useCache ? promise.then((response) => {
+            Logger.log("[Server] Response from", url, response);
+            Storage.set(path, response);
+            return response;
+        }) : promise.then((response) => {
+            Logger.log("[Server] Response from", url, response);
+            return response;
+        })
     }
 
-    static get(path) {
-        return this._request(path, "GET", null);
+    static get(path, useCache = true) {
+        return (useCache && Storage.get(path)) ?
+            Promise.resolve(Storage.get(path)) : this._request(path, "GET", null, useCache);
     }
 
     static post(path, data) {
diff --git a/package.json b/package.json
index bbbc8f9b..8ec954ec 100755
--- a/package.json
+++ b/package.json
@@ -6,7 +6,7 @@
   "scripts": {
     "build": "webpack --config webpack.prod.config.js --progress --colors",
     "build-production": "webpack -p --config webpack.prod.config.js --progress --colors",
-    "webpack": "webpack -p --progress --display-error-details --config webpack.config.js --watch",
+    "webpack": "webpack --progress --display-error-details --config webpack.config.js --watch",
     "watch": "node server.js",
     "karma": "karma start"
   },
-- 
GitLab