| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- /**
- * @file utils.js
- * @description Utility functions for making API requests and handling responses.
- */
- "use strict";
- /**
- * Fetches a resource from the server with authentication token.
- *
- * @async
- * @param {string} url - The URL of the resource to fetch.
- * @param {Object} options - Options for the fetch request (e.g. method, body).
- * @returns {Promise<Object>} A promise resolving to the response data.
- */
- async function fetchWithToken(url, options) {
- const authToken = localStorage.getItem('token');
- return await fetch(url, {...options, headers: {
- 'Authorization': `Bearer ${authToken}`,
- 'Content-Type': 'application/json',
- 'Cache-Control': 'no-cache, no-store',
- }});
- }
- /**
- * Fetches a resource from the server without authentication token.
- *
- * @async
- * @param {string} url - The URL of the resource to fetch.
- * @param {Object} options - Options for the fetch request (e.g. method, body).
- * @returns {Promise<Object>} A promise resolving to the response data.
- */
- async function fetchRegular(url, options) {
- return await fetch(url, {...options, headers: {
- 'Content-Type': 'application/json',
- 'Cache-Control': 'no-cache, no-store',
- }});
- }
- /**
- * Formats a time as HH:MM string.
- *
- * @param {Date} date - The date to format.
- * @returns {string} The formatted time string (e.g. "09:00").
- */
- function formatTime(date) {
- const hours = date.getHours().toString().padStart(2, '0');
- const minutes = date.getMinutes().toString().padStart(2, '0');
- return `${hours}:${minutes}`;
- }
- /**
- * Gets the time span between two dates.
- *
- * @param {Date} start - The start date.
- * @param {Date} end - The end date.
- * @returns {string} The time span string (e.g. "09:00 to 10:00").
- */
- function getTimeSpan(start, end) {
- return `${formatTime(new Date(start))} to ${formatTime(new Date(end))}`;
- }
- /**
- * Parses the response data and redirects if necessary.
- *
- * @async
- * @param {Response} response - The server response.
- * @returns {Promise<Object>} A promise resolving to the parsed response data, or null if a redirect was taken.
- */
- async function parseOrRedirect(response) {
- if (response.status === 401) {
- // Handle unauthorized request (redirect to login page)
- window.location.replace("/html/auth.html");
- return;
- }
- if (response.status === 410) {
- // Handle deprecated resource (redirect to deprecated page)
- window.location.replace("/html/410.html");
- return;
- }
- const js = await response.json();
- if (!response.ok) {
- // Handle non-200 status code (redirect to error page)
- window.location.replace("/html/404.html");
- }
- return js;
- }
- export { fetchWithToken, getTimeSpan, parseOrRedirect, fetchRegular };
|