Skip to content

Commit

Permalink
**Major refactor**: _Enhance proxy URL configuration for improved fle…
Browse files Browse the repository at this point in the history
…xibility and reliability._

- **Refactor** `proxy URL handling`,
- **Remove** `export` from `exchange-token`
- **Eliminate** `construction warning` on profile
  • Loading branch information
akionii committed May 2, 2024
1 parent ba1ebad commit d72ccc0
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 53 deletions.
14 changes: 7 additions & 7 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
# Backend Server URL
# Backend Server URL [NOT OPTIONAL]
# Description: Base URL for the primary backend server used for API requests to fetch anime data, metadata, and other related information.
# Example: VITE_BACKEND_URL="https://public-miruro-consumet-api.vercel.app/"
VITE_BACKEND_URL="https://public-miruro-consumet-api.vercel.app/"

# Episode Skip Times URL
# Episode Skip Times URL [OPTIONAL]
# Description: URL for fetching episode skip times to help users skip intros, outros, and recaps.
# Example & Current Setting: VITE_SKIP_TIMES="https://api.aniskip.com/"
VITE_SKIP_TIMES="https://api.aniskip.com/"

# Proxy Server URL
# Proxy Server URL [OPTIONAL]
# Description: URL of the proxy server used to circumvent CORS issues or when making requests to external services that do not support CORS.
# Example: VITE_PROXY_URL="https://corsproxy.io/"
VITE_PROXY_URL="https://corsproxy.io/"

# API Key
# API Key [OPTIONAL]
# Description: The API key used for authenticating requests to secured endpoints. This key ensures that only authorized users and applications can access specific API functions.
# To generate a secure API key, you can use the command: openssl rand -base64 32
# Example: VITE_API_KEY="your_secret_api_key_here"
VITE_API_KEY=""

# Server Port
# Server Port [OPTIONAL]
# Description: The port number on which the server will listen. Important for server configuration in both development and production environments.
# Example & Default: PORT=5173
VITE_PORT=5173

# Google Analytics
# Google Analytics [OPTIONAL]
# Description: Google Analytics Measurement ID used for tracking website analytics and user interactions.
# This ID is provided by Google Analytics and is used to initialize the analytics library in the frontend application.
VITE_GA_MEASUREMENT_ID=""

# AniList Configuration (Optional)
# AniList Configuration [OPTIONAL]
# Description: Configuration for connecting to AniList API.
# Example & Current Setting: VITE_DEPLOY_PLATFORM="VERCEL"
VITE_DEPLOY_PLATFORM="VERCEL"
Expand Down
2 changes: 1 addition & 1 deletion api/exchange-token.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios';
import type { VercelRequest, VercelResponse } from '@vercel/node';

export default async function exchangeAccessToken(req: VercelRequest, res: VercelResponse) {
async (req: VercelRequest, res: VercelResponse) => {
if (req.method !== 'POST') {
res.status(405).send('Method Not Allowed');
return;
Expand Down
29 changes: 16 additions & 13 deletions src/hooks/useApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,17 @@ const BASE_URL = ensureUrlEndsWithSlash(
const SKIP_TIMES = ensureUrlEndsWithSlash(
import.meta.env.VITE_SKIP_TIMES as string,
);
const PROXY_URL = ensureUrlEndsWithSlash(
import.meta.env.VITE_PROXY_URL as string,
);
let PROXY_URL = import.meta.env.VITE_PROXY_URL; // Default to an empty string if no proxy URL is provided
// Check if the proxy URL is provided and ensure it ends with a slash
if (PROXY_URL) {
PROXY_URL = ensureUrlEndsWithSlash(import.meta.env.VITE_PROXY_URL as string);
}

const API_KEY = import.meta.env.VITE_API_KEY as string;

// Axios instance
const axiosInstance = axios.create({
baseURL: PROXY_URL,
baseURL: PROXY_URL || undefined,
timeout: 10000,
headers: {
'X-API-Key': API_KEY, // Assuming your API expects the key in this header
Expand Down Expand Up @@ -169,33 +171,34 @@ async function fetchFromProxy(url: string, cache: any, cacheKey: string) {
// Attempt to retrieve the cached response using the cacheKey
const cachedResponse = cache.get(cacheKey);
if (cachedResponse) {
// console.log(`Serving from cache for key: ${cacheKey}`); // Debugging: Confirming cache hit
return cachedResponse; // Return the cached response if available
}

// Proceed with the network request if no cached response is found
const response = await axiosInstance.get('', { params: { url } }); // Adjust based on how the proxy expects to receive the original URL
// Adjust request parameters based on PROXY_URL's availability
const requestConfig = PROXY_URL
? { params: { url } } // If PROXY_URL is defined, send the original URL as a parameter
: {}; // If PROXY_URL is not defined, make a direct request

// Proceed with the network request
const response = await axiosInstance.get(PROXY_URL ? '' : url, requestConfig);

// After obtaining the response, verify it for errors or empty data as before
// After obtaining the response, verify it for errors or empty data
if (
response.status !== 200 ||
(response.data.statusCode && response.data.statusCode >= 400)
) {
const errorMessage = response.data.message || 'Unknown server error';
throw new Error(
`Server error: ${
response.data.statusCode || response.status
`Server error: ${response.data.statusCode || response.status
} ${errorMessage}`,
);
}

// Assuming response data is valid, store it in the cache
cache.set(cacheKey, response.data); // Cache the new data using the cacheKey
// console.log(`Caching new data for key: ${cacheKey}`); // Debugging: Confirming new data is cached
cache.set(cacheKey, response.data);

return response.data; // Return the newly fetched data
} catch (error) {
// Handle errors from Axios or due to invalid responses
handleError(error, 'data');
throw error; // Rethrow the error for the caller to handle
}
Expand Down
32 changes: 0 additions & 32 deletions src/pages/Profile.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import React, { useEffect } from 'react';
import styled from 'styled-components';
import { LuConstruction } from 'react-icons/lu';
import { IoLogOutOutline } from 'react-icons/io5';
import Image404URL from '/src/assets/404.webp';
import { useAuth, EpisodeCard, WatchingAnilist } from '../index';
import { SiAnilist } from 'react-icons/si';
import { CgProfile } from 'react-icons/cg';
Expand Down Expand Up @@ -49,20 +47,6 @@ const ProfileContainer = styled.div`
}
`;

const WarningMessage = styled.div`
background-color: var(--global-div-tr);
padding: 0.5rem;
border-radius: var(--global-border-radius);
text-align: center;
font-size: 0.9rem;
flex: 1; // Take up equal space when next to each other
@media (max-width: 500px) {
img {
display: none;
}
}
`;

const PreferencesContainer = styled.div`
max-width: 80rem;
margin: auto;
Expand Down Expand Up @@ -177,22 +161,6 @@ export const Profile: React.FC = () => {
</UserInfoContainer>
)}
</ProfileContainer>
<WarningMessage>
<LuConstruction style={{ color: 'orange' }} />
This page is currently{' '}
<strong style={{ color: 'orange' }}>under construction</strong>. We
appreciate your patience as we work to bring you new features!
<br />
<br />
<img
src={Image404URL}
alt='404 Error'
style={{
borderRadius: 'var(--global-border-radius)',
maxWidth: '100%',
}}
/>
</WarningMessage>
</TopContainer>
<EpisodeCard />
<WatchingAnilist />
Expand Down

0 comments on commit d72ccc0

Please sign in to comment.