Liontix 11 miesięcy temu
rodzic
commit
6123ab8887

+ 3 - 24
public/javascripts/appointments.js

@@ -1,6 +1,6 @@
 "use strict";
 
-import { fetchWithToken } from "./utils.js";
+import {fetchWithToken, getTimeSpan, parseOrRedirect} from "./utils.js";
 
 let last_clicked = "";
 let click_counter = 0;
@@ -10,17 +10,7 @@ window.addEventListener("load", async function () {
     await fetchAppointments();
 });
 
-// Function to format time as HH:MM
-function formatTime(date) {
-    const hours = date.getUTCHours().toString().padStart(2, '0');
-    const minutes = date.getUTCMinutes().toString().padStart(2, '0');
-    return `${hours}:${minutes}`;
-}
 
-// Function to get the time span (e.g., 09:00 to 10:00)
-function getTimeSpan(start, end) {
-    return `${formatTime(new Date(start))} to ${formatTime(new Date(end))}`;
-}
 
 // Render the appointments into the table
 function renderAppointments(data) {
@@ -96,10 +86,7 @@ async function deleteAppointment(appointmentId) {
         method: 'DELETE',
         body: JSON.stringify({appointmentId: appointmentId})
     });
-    if (response.status === 401) {
-        window.location.replace("/html/auth.html");
-        return;
-    }
+    await parseOrRedirect(response);
 
     if (response.ok) {
         await fetchAppointments();
@@ -108,16 +95,8 @@ async function deleteAppointment(appointmentId) {
 
 async function fetchAppointments() {
     const response = await fetchWithToken("/api/users/appointments");
-    if (response.status === 401) {
-        window.location.replace("/html/auth.html");
-        return;
-    }
-
-    const js = await response.json();
-    if (!response.ok) {
-        window.location.replace("/html/404.html");
-    }
 
+    const js = await parseOrRedirect(response);
 
     renderAppointments(js);
 }

+ 3 - 22
public/javascripts/bookings.js

@@ -1,4 +1,4 @@
-import { fetchWithToken } from "./utils.js";
+import {fetchWithToken, getTimeSpan, parseOrRedirect} from "./utils.js";
 "use strict";
 
 window.addEventListener("load", async function () {
@@ -59,24 +59,13 @@ function displayAppointmentDetails(appointmentData) {
     appointmentInfo.appendChild(timeSpan);
 }
 
-// Helper function to format the time span
-function getTimeSpan(startDate, endDate) {
-    const start = new Date(startDate).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
-    const end = new Date(endDate).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
-    return `${start} to ${end}`;
-}
-
 async function getAppointment(appointment) {
     const options = {method: 'GET', headers: {'User-Agent': 'insomnia/10.0.0'}};
 
     const response = await fetch(`/api/schedule?isUser=true&appointmentId=${appointment}`, options)
         .catch(err => console.error('error:' + err));
 
-    if (response.status === 404) {
-        window.location.replace("/html/404.html");
-    }
-
-    const js = await response.json();
+    const js = await parseOrRedirect(response);
     displayAppointmentDetails(js);
 }
 
@@ -112,14 +101,6 @@ function renderBookings(data) {
 
 async function fetchBookings(appointmentId) {
     const response = await fetchWithToken(`/api/users/bookings?appointmentId=${appointmentId}`);
-    if (response.status === 401) {
-        window.location.replace("/html/auth.html");
-        return;
-    }
-
-    const js = await response.json();
-    if (!response.ok) {
-        window.location.replace("/html/404.html");
-    }
+    const js = await parseOrRedirect(response);
     renderBookings(js);
 }

+ 3 - 12
public/javascripts/creator-appointments.js

@@ -1,5 +1,7 @@
 "use strict";
 
+import {fetchWithToken, parseOrRedirect} from "./utils.js";
+
 const appointmentErrorParagraph = document.getElementById("appointment-error");
 const appointmentSuccessParagraph = document.getElementById("appointment-success");
 const titleInput = document.getElementById('title');
@@ -31,14 +33,6 @@ window.addEventListener("load", async function() {
     })
 });
 
-async function fetchWithToken(url, options) {
-    const authToken = localStorage.getItem('token');
-    return await fetch(url, {...options, headers: {
-            'Authorization': `Bearer ${authToken}`,
-            'Content-Type': 'application/json',
-        }});
-}
-
 async function displayAppointment(data) {
     titleInput.value = data.title;
     descriptionInput.value = data.description;
@@ -54,10 +48,7 @@ async function loadAppointment(appointment) {
     const response = await fetch(`/api/schedule?appointmentId=${appointment}`, options)
         .catch(err => console.error('error:' + err));
 
-    if (response.status === 404) {
-        window.location.replace("/html/404.html");
-    }
-    const js = await response.json();
+    const js = await parseOrRedirect(response);
     await displayAppointment(js);
 }
 

+ 3 - 22
public/javascripts/schedule.js

@@ -1,5 +1,7 @@
 "use strict";
 
+import {getTimeSpan, parseOrRedirect} from "./utils.js";
+
 let appointment;
 const errorParagraph = document.getElementById('appointment-error');
 const successParagraph = document.getElementById('appointment-success');
@@ -18,34 +20,13 @@ window.addEventListener("load", async function () {
     await getAppointment();
 });
 
-// Function to format time as HH:MM
-function formatTime(date) {
-    const hours = date.getHours().toString().padStart(2, '0');  // Get hours and ensure two digits
-    const minutes = date.getMinutes().toString().padStart(2, '0');  // Get minutes and ensure two digits
-    return `${hours}:${minutes}`;
-}
-
-// Function to get time span (from 11:00 to 12:00 format)
-function getTimeSpan(start, end) {
-    const startTime = formatTime(start);
-    const endTime = formatTime(end);
-    return `${startTime} to ${endTime}`;
-}
-
 async function getAppointment() {
     let options = {method: 'GET', headers: {'User-Agent': 'insomnia/10.0.0'}};
 
     const response = await fetch(`/api/schedule?appointmentId=${appointment}`, options)
         .catch(err => console.error('error:' + err));
 
-    if (response.status === 404) {
-        window.location.replace("/html/404.html");
-    }
-
-    if (response.status === 410) {
-        window.location.replace("/html/410.html");
-    }
-    const js = await response.json();
+    const js = await parseOrRedirect(response);
     displayAppointmentDetails(js);
 }
 

+ 31 - 1
public/javascripts/utils.js

@@ -8,5 +8,35 @@ async function fetchWithToken(url, options) {
         }});
 }
 
+// Function to format time as HH:MM
+function formatTime(date) {
+    const hours = date.getUTCHours().toString().padStart(2, '0');
+    const minutes = date.getUTCMinutes().toString().padStart(2, '0');
+    return `${hours}:${minutes}`;
+}
+
+// Function to get the time span (e.g., 09:00 to 10:00)
+function getTimeSpan(start, end) {
+    return `${formatTime(new Date(start))} to ${formatTime(new Date(end))}`;
+}
+
+async function parseOrRedirect(response) {
+    if (response.status === 401) {
+        window.location.replace("/html/auth.html");
+        return;
+    }
+
+    if (response.status === 410) {
+        window.location.replace("/html/410.html");
+        return;
+    }
+
+    const js = await response.json();
+    if (!response.ok) {
+        window.location.replace("/html/404.html");
+    }
+
+    return js;
+}
 
-export { fetchWithToken };
+export { fetchWithToken, getTimeSpan, parseOrRedirect };