Fakultas Ilmu Komputer UI

Commit 8ff83265 authored by Zamil Majdy's avatar Zamil Majdy
Browse files

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

parent c7d8cf8f
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) {
......
......@@ -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"
},
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment