Fakultas Ilmu Komputer UI

Skip to content
Snippets Groups Projects
Commit 8ff83265 authored by Zamil Majdy's avatar Zamil Majdy
Browse files

[#140382397] #6 Add caching mechanism on Server.jsx library

parent c7d8cf8f
Branches
No related tags found
No related merge requests found
import Logger from './logger'; import Logger from "./logger";
import Storage from "./storage";
export default class Server { export default class Server {
static getCookie(name) { static getCookie(name) {
...@@ -17,7 +18,7 @@ export default class Server { ...@@ -17,7 +18,7 @@ export default class Server {
return cookieValue; return cookieValue;
} }
static _request(path, method, data) { static _request(path, method, data, useCache = false) {
let url = "/api" + path; let url = "/api" + path;
let csrftoken = this.getCookie("csrftoken"); let csrftoken = this.getCookie("csrftoken");
...@@ -34,24 +35,30 @@ export default class Server { ...@@ -34,24 +35,30 @@ export default class Server {
}; };
let request = fetch(url, requestData); let request = fetch(url, requestData);
return request.then((response) => { let promise = request.then((response) => {
// Logger.log("[Server] Calling", url, response); // Logger.log("[Server] Calling", url, response);
if (response.status < 200 || response.status > 399) { if (response.status < 200 || response.status > 399) {
Logger.log(response);
throw response; throw response;
} }
if (response.status === 204) { if (response.status === 204) {
return response; return response;
} }
return response.json(); 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) { static get(path, useCache = true) {
return this._request(path, "GET", null); return (useCache && Storage.get(path)) ?
Promise.resolve(Storage.get(path)) : this._request(path, "GET", null, useCache);
} }
static post(path, data) { static post(path, data) {
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
"scripts": { "scripts": {
"build": "webpack --config webpack.prod.config.js --progress --colors", "build": "webpack --config webpack.prod.config.js --progress --colors",
"build-production": "webpack -p --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", "watch": "node server.js",
"karma": "karma start" "karma": "karma start"
}, },
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment