From fc03a2e90858f711a7a9585b0ef274624a31163e Mon Sep 17 00:00:00 2001
From: Johannes Buechele <johannes@bujo.at>
Date: Wed, 9 Aug 2023 14:40:08 +0200
Subject: [PATCH] refactored api service, get new token if invalid

---
 .../components/bundel/UserWorkListElement.jsx |   6 +-
 .../registerwork/registerworkFileUpload.jsx   |   2 +-
 Frontend/src/index.js                         |   4 +-
 Frontend/src/pages/MyWorksPage.jsx            |   3 +-
 Frontend/src/pages/RegisterWorkPage.jsx       |   2 +-
 Frontend/src/services/ApiService.js           | 234 +++++-------------
 Frontend/src/services/HttpClient.js           |  38 +++
 Frontend/src/services/HttpClientService.js    |  68 -----
 Frontend/src/services/HttpService.js          |  30 ---
 9 files changed, 112 insertions(+), 275 deletions(-)
 create mode 100644 Frontend/src/services/HttpClient.js
 delete mode 100644 Frontend/src/services/HttpClientService.js
 delete mode 100644 Frontend/src/services/HttpService.js

diff --git a/Frontend/src/components/bundel/UserWorkListElement.jsx b/Frontend/src/components/bundel/UserWorkListElement.jsx
index d63fab2..a5e6981 100644
--- a/Frontend/src/components/bundel/UserWorkListElement.jsx
+++ b/Frontend/src/components/bundel/UserWorkListElement.jsx
@@ -136,7 +136,7 @@ const UserWorkListElement = (props) => {
                     <div
                       onClick={(event) => {
                         event.stopPropagation();
-                        ApiService.getDownload(
+                        ApiService.downloadWork(
                           props.userWork.id,
                           props.userWork.filename,
                         );
@@ -156,7 +156,7 @@ const UserWorkListElement = (props) => {
                       onClick={(event) => {
                         console.log(props.userWork.grid);
                         event.stopPropagation();
-                        ApiService.getPublicDownload(
+                        ApiService.downloadPublicWork(
                           props.userWork.grid,
                           props.userWork.filename,
                         );
@@ -175,7 +175,7 @@ const UserWorkListElement = (props) => {
                     <div
                       onClick={(event) => {
                         event.stopPropagation();
-                        ApiService.getCertificate(props.userWork.id);
+                        ApiService.downloadCertificate(props.userWork.id);
                       }}
                     >
                       <div class="flex items-center justify-center">
diff --git a/Frontend/src/components/registerwork/registerworkFileUpload.jsx b/Frontend/src/components/registerwork/registerworkFileUpload.jsx
index 1c1bb33..49da025 100644
--- a/Frontend/src/components/registerwork/registerworkFileUpload.jsx
+++ b/Frontend/src/components/registerwork/registerworkFileUpload.jsx
@@ -25,7 +25,7 @@ const RegisterWorkFileUpload = (props) => {
       reader.readAsArrayBuffer(file);
       props.onSetFilename(file.name);
 
-      ApiService.getPresignedAsset(
+      ApiService.uploadWork(
         file.name,
         file,
         props.onSetPresignedURL,
diff --git a/Frontend/src/index.js b/Frontend/src/index.js
index e088d02..62f077e 100644
--- a/Frontend/src/index.js
+++ b/Frontend/src/index.js
@@ -5,7 +5,7 @@ import "./index.css";
 import App from "./App";
 import { I18nextProvider } from "react-i18next";
 import UserService from "./services/UserService";
-import HttpService from "./services/HttpService";
+import HttpClient from "./services/HttpClient";
 import LanguageService from "./services/LanguageService";
 
 //import reportWebVitals from './reportWebVitals';
@@ -27,7 +27,7 @@ const renderApp = () =>
   );
 
 UserService.initKeycloak(renderApp);
-HttpService.configure();
+HttpClient.configure();
 
 // If you want to start measuring performance in your app, pass a function
 // to log results (for example: reportWebVitals(console.log))
diff --git a/Frontend/src/pages/MyWorksPage.jsx b/Frontend/src/pages/MyWorksPage.jsx
index 5d41b3b..5235285 100644
--- a/Frontend/src/pages/MyWorksPage.jsx
+++ b/Frontend/src/pages/MyWorksPage.jsx
@@ -21,7 +21,8 @@ const MyWorksPage = () => {
     const fetchData = async () => {
       setIsLoading(true);
       try {
-        const result = await ApiService.getUserWorkList2(page, itemsPerPage);
+        const result = await ApiService.getUserWorkList(page, itemsPerPage);
+        console.log(result)
         setUserWorkList(result?.content);
         setTotalPages(result?.totalPages);
         setTotalElements(result?.totalElements);
diff --git a/Frontend/src/pages/RegisterWorkPage.jsx b/Frontend/src/pages/RegisterWorkPage.jsx
index d88f9de..ec81113 100644
--- a/Frontend/src/pages/RegisterWorkPage.jsx
+++ b/Frontend/src/pages/RegisterWorkPage.jsx
@@ -431,7 +431,7 @@ const RegisterWorkPage = () => {
   const onSendRegisterFinally = () => {
     console.log(registerWorkData);
 
-    ApiService.postAsset(registerWorkData).then(() => navigate("/myworks"));
+    ApiService.registerWork(registerWorkData).then(() => navigate("/myworks"));
   };
   //#endregion
 
diff --git a/Frontend/src/services/ApiService.js b/Frontend/src/services/ApiService.js
index f399b43..0817afb 100644
--- a/Frontend/src/services/ApiService.js
+++ b/Frontend/src/services/ApiService.js
@@ -1,25 +1,16 @@
-import HttpClientService from "./HttpClientService";
+import HttpClient from "./HttpClient";
 import UserService from "./UserService";
 import { saveAs } from "file-saver";
 import { REACT_APP_API } from "../config";
 
-
-const httpClient = new HttpClientService(REACT_APP_API);
-
-
-const getUserWorkList2 = async (page, size) => {
+const getUserWorkList = async (page, size) => {
   const keycloakUserId = UserService.getUserId();
   const url = `/users/${keycloakUserId}/works?page=${page}&size=${size}`;
-  const headers = {
-    "Access-Control-Allow-Origin": "*",
-    "Content-Type": "application/json",
-    "Authorization": `Bearer ${UserService.getToken()}`,
-  };
 
   try {
-    const result = await httpClient.get(url, headers);
-    console.log(result);
-    return result;
+    const result = await HttpClient.get(url);
+
+    return result.data;
   } catch (error) {
     console.error("Error:", error);
     throw error;
@@ -61,15 +52,10 @@ const getPublicWorkList = async (
   // Remove trailing '&' if there are any parameters
   url = url.endsWith("&") ? url.slice(0, -1) : url;
 
-  const headers = {
-    "Access-Control-Allow-Origin": "*",
-    "Content-Type": "application/json",
-  };
-
   try {
-    const result = await httpClient.get(url, headers);
-    console.log(result);
-    return result;
+    const result = await HttpClient.get(url);
+
+    return result.data;
   } catch (error) {
     console.error("Error:", error);
     throw error;
@@ -91,179 +77,89 @@ const getLicenceList = async () => {
   }
 };
 
-const getCertificate = async (workId) => {
-  await fetch(`${REACT_APP_API}/works/${workId}/certificate`, {
-    method: "GET",
-    headers: {
-      "Access-Control-Allow-Origin": "*",
-      "Authorization": `Bearer ${UserService.getToken()}`,
-    },
-  })
-    .then(async (response) => {
-      const blob = await response.blob();
-      saveAs(blob, `${workId}.pdf`);
-    })
-    .catch((error) => {
-      console.error("Error:", error);
+const downloadCertificate = async (workId) => {
+  try {
+    const response = await HttpClient.get(`/works/${workId}/certificate`, {
+      responseType: "blob",
     });
+    saveAs(response.data, `${workId}.pdf`);
+  } catch (error) {
+    console.error("Error:", error);
+    throw error;
+  }
 };
 
-const getDownload = async (workId, filename) => {
-  await fetch(`${REACT_APP_API}/works/${workId}/download`, {
-    method: "GET",
-    headers: {
-      "Access-Control-Allow-Origin": "*",
-      "Authorization": `Bearer ${UserService.getToken()}`,
-    },
-  })
-    .then(async (response) => {
-      const blob = await response.blob();
-      saveAs(blob, `${filename}`);
-    })
-    .catch((error) => {
-      console.error("Error:", error);
+const downloadWork = async (workId, filename) => {
+  try {
+    const response = await HttpClient.get(`/works/${workId}/download`, {
+      responseType: "blob",
     });
+
+    saveAs(response.data, `${filename}`);
+  } catch (error) {
+    console.error("Error:", error);
+    throw error;
+  }
 };
 
-const getPublicDownload = async (grid) => {
-  window.open(`${REACT_APP_API}/works/public/${grid}/download`, "_blank")
+const downloadPublicWork = async (grid) => {
+  window.open(`${REACT_APP_API}/works/public/${grid}/download`, "_blank");
 };
 
-const getPresignedAsset = async (
+const uploadWork = async (
   filename,
   file,
   onSetPresignedURL,
   onSetPrefix,
   setLoading,
 ) => {
-  var keycloakUserId = UserService.getUserId();
-  await fetch(
-    `${REACT_APP_API}/files/upload/presigned-url?filename=${filename}&userId=${keycloakUserId}`,
-    {
-      method: "GET",
-      headers: {
-        "Access-Control-Allow-Origin": "*",
-        "Content-Type": "application/json",
-        "Authorization": `Bearer ${UserService.getToken()}`,
-      },
-    },
-  )
-    .then(async (response) => {
-      if (response.status === 200) {
-        var result = await response.json();
-        onSetPresignedURL(result.url);
-        onSetPrefix(result.prefix);
-        console.log(result);
-        return result;
-      }
-    })
-    .then(async (result) => {
-      putAsset(result.url, file, setLoading);
-    })
-
-    .catch((error) => {
-      console.error("Error:", error);
-    });
-};
+  try {
+    const keycloakUserId = UserService.getUserId();
+    const response = await HttpClient.get(
+      `/files/upload/presigned-url?filename=${filename}&userId=${keycloakUserId}`,
+    );
+    const presignedUploadUrl = response.data?.url;
+    const prefix = response.data?.prefix;
 
-const putAsset = async (url, file, setLoading) => {
-  await fetch(url, {
-    method: "PUT",
-    headers: {
-      "Access-Control-Allow-Origin": "*",
-    },
-    body: file,
-  })
-    .then(async (response) => {
-      console.log(response);
-      if (response.status === 200) {
-        console.log(response.text());
+    onSetPresignedURL(presignedUploadUrl);
+    onSetPrefix(prefix);
 
-        setLoading(false);
-        return response;
-      }
-      console.log(response.text());
-    })
-    .then((data) => {
-      console.log(data);
-    })
-    .catch((error) => {
-      console.error("Error:", error);
-    });
+    await uploadAsset(presignedUploadUrl, file, setLoading);
+  } catch (error) {
+    console.error("Error:", error);
+    throw error;
+  }
 };
 
-const postAsset = async (raw) => {
-  console.log(JSON.stringify(raw));
-
-  await fetch(`${REACT_APP_API}/works/register`, {
-    method: "POST",
-    headers: {
-      "Content-Type": "application/json",
-      "Authorization": `Bearer ${UserService.getToken()}`,
-    },
-    body: JSON.stringify(raw),
-  })
-    .then(async (response) => {
-      if (response.status === 200) {
-        return response;
-      }
-    })
-    .catch((error) => {
-      console.error("Error:", error);
-    });
+const uploadAsset = async (url, file, setLoading) => {
+  try {
+    await HttpClient.put(url, file);
+    setLoading(false);
+  } catch (error) {
+    console.error("Error:", error);
+    throw error;
+  }
 };
 
-const getUserWorkList = async (
-  page,
-  size,
-  setUserWorkList,
-  setTotalPages,
-  setTotalElements,
-  setPagination,
-) => {
-  var keycloakUserId = UserService.getUserId();
-
-  await fetch(
-    `${REACT_APP_API}/users/${keycloakUserId}/works?page=${page}&size=${size}`,
-    {
-      method: "GET",
-      headers: {
-        "Access-Control-Allow-Origin": "*",
-        "Content-Type": "application/json",
-        "Authorization": `Bearer ${UserService.getToken()}`,
-      },
-    },
-  )
-    .then(async (response) => {
-      if (response.status === 200) {
-        console.log(response);
-        var result = await response.json();
-        setUserWorkList(result);
-        setTotalPages(result.totalPages);
-        setTotalElements(result.totalElements);
-        setPagination(result);
-        return result;
-      }
-    })
-    .then(async (result) => {
-      setUserWorkList(result.content);
-      setPagination(result.pageable);
-    })
-    .catch((error) => {
-      console.error("Error:", error);
-    });
+const registerWork = async (raw) => {
+  try {
+    const response = await HttpClient.post("/works/register", JSON.stringify(raw));
+    return response.data;
+  } catch (error) {
+    console.error("Error:", error);
+    throw error;
+  }
 };
 
 const ApiService = {
-  postAsset,
-  getCertificate,
-  getDownload,
-  getPublicDownload,
+  registerWork,
+  downloadCertificate,
+  downloadWork,
+  downloadPublicWork,
   getPublicWorkList,
   getUserWorkList,
-  getUserWorkList2,
   getLicenceList,
-  getPresignedAsset,
+  uploadWork,
 };
 
 export default ApiService;
diff --git a/Frontend/src/services/HttpClient.js b/Frontend/src/services/HttpClient.js
new file mode 100644
index 0000000..ab88d98
--- /dev/null
+++ b/Frontend/src/services/HttpClient.js
@@ -0,0 +1,38 @@
+import axios from "axios";
+import UserService from "./UserService";
+import { REACT_APP_API } from "../config";
+
+const _axios = axios.create({
+  baseURL: REACT_APP_API,
+});
+
+const configure = () => {
+  _axios.interceptors.request.use((config) => {
+    const cb = () => {
+      config.headers.Authorization = `Bearer ${UserService.getToken()}`;
+      return Promise.resolve(config);
+    };
+    return UserService.updateToken(cb);
+  });
+};
+
+const get = async (url, config = {}) => {
+  return await _axios.get(url, config);
+};
+
+const post = async (url, data, config = {}) => {
+  return await _axios.post(url, data,  config);
+};
+
+const put = async (url, data, config = {}) => {
+  return await _axios.put(url, data, config);
+};
+
+const HttpClient = {
+  configure,
+  get,
+  post,
+  put
+};
+
+export default HttpClient;
diff --git a/Frontend/src/services/HttpClientService.js b/Frontend/src/services/HttpClientService.js
deleted file mode 100644
index 72eea5b..0000000
--- a/Frontend/src/services/HttpClientService.js
+++ /dev/null
@@ -1,68 +0,0 @@
-export default class HttpClientService {
-  constructor(baseURL) {
-    this.baseURL = baseURL;
-    this.defaultHeaders = {
-      "Content-Type": "application/json",
-    };
-  }
-
-  async get(url, headers = {}) {
-    const options = {
-      method: "GET",
-      headers: { ...this.defaultHeaders, ...headers },
-    };
-    const response = await fetch(this.baseURL + url, options);
-    console.log(response);
-    if (!response.ok) {
-      throw new Error(`HTTP error! status: ${response.status}`);
-    }
-    return response.json();
-  }
-
-  async post(url, data, headers = {}) {
-    const options = {
-      method: "POST",
-      headers: { ...this.defaultHeaders, ...headers },
-      body: JSON.stringify(data),
-    };
-
-    const response = await fetch(this.baseURL + url, options);
-
-    if (!response.ok) {
-      throw new Error(`HTTP error! status: ${response.status}`);
-    }
-
-    return response.json();
-  }
-
-  async put(url, data, headers = {}) {
-    const options = {
-      method: "PUT",
-      headers: { ...this.defaultHeaders, ...headers },
-      body: JSON.stringify(data),
-    };
-
-    const response = await fetch(this.baseURL + url, options);
-
-    if (!response.ok) {
-      throw new Error(`HTTP error! status: ${response.status}`);
-    }
-
-    return response.json();
-  }
-
-  async delete(url, headers = {}) {
-    const options = {
-      method: "DELETE",
-      headers: { ...this.defaultHeaders, ...headers },
-    };
-
-    const response = await fetch(this.baseURL + url, options);
-
-    if (!response.ok) {
-      throw new Error(`HTTP error! status: ${response.status}`);
-    }
-
-    return response.json();
-  }
-}
diff --git a/Frontend/src/services/HttpService.js b/Frontend/src/services/HttpService.js
deleted file mode 100644
index ed478ce..0000000
--- a/Frontend/src/services/HttpService.js
+++ /dev/null
@@ -1,30 +0,0 @@
-import axios from "axios";
-import UserService from "./UserService";
-
-const HttpMethods = {
-  GET: "GET",
-  POST: "POST",
-  DELETE: "DELETE",
-};
-
-const _axios = axios.create();
-
-const configure = () => {
-  _axios.interceptors.request.use((config) => {
-    const cb = () => {
-      config.headers.Authorization = `Bearer ${UserService.getToken()}`;
-      return Promise.resolve(config);
-    };
-    return UserService.updateToken(cb);
-  });
-};
-
-const getAxiosClient = () => _axios;
-
-const HttpService = {
-  HttpMethods,
-  configure,
-  getAxiosClient,
-};
-
-export default HttpService;
-- 
GitLab