Perps-Terminal / frontend /src /api /client.ts
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
6.58 kB
import axios from 'axios';
export const DEFAULT_CLOUD_URL = 'https://agus1111-perps-terminal.hf.space';
export const API_TOKEN_STORAGE_KEY = 'perps_api_token';
export function getApiToken(): string {
if (typeof window !== 'undefined') {
const token = localStorage.getItem(API_TOKEN_STORAGE_KEY);
if (token) return token.trim();
}
return '';
}
export function setApiToken(token: string): void {
const clean = token.trim();
if (typeof window !== 'undefined') {
if (clean) {
localStorage.setItem(API_TOKEN_STORAGE_KEY, clean);
} else {
localStorage.removeItem(API_TOKEN_STORAGE_KEY);
}
window.dispatchEvent(new Event('perps_api_token_changed'));
}
}
export function isNativeApp(): boolean {
if (typeof window === 'undefined') return false;
return Boolean(
(window as any).Capacitor?.isNativePlatform?.() ||
(window as any).Capacitor ||
window.location.protocol === 'capacitor:' ||
window.location.protocol === 'file:'
);
}
export function getServerUrl(): string {
if (typeof window !== 'undefined') {
const custom = localStorage.getItem('perps_server_url');
if (custom) return custom.trim().replace(/\/+$/, '');
}
if (import.meta.env.VITE_API_URL) {
return import.meta.env.VITE_API_URL.replace(/\/+$/, '');
}
// If inside Capacitor / APK, default to live cloud backend
if (isNativeApp()) {
return DEFAULT_CLOUD_URL;
}
// Local dev with port 5173
if (typeof window !== 'undefined' && window.location.port === '5173') {
return 'http://127.0.0.1:8000';
}
// Standard web relative (eliminates CORS on unified deployment)
return '';
}
export function setServerUrl(url: string): void {
const clean = url.trim().replace(/\/+$/, '');
if (clean) {
localStorage.setItem('perps_server_url', clean);
} else {
localStorage.removeItem('perps_server_url');
}
if (typeof window !== 'undefined') {
window.dispatchEvent(new Event('perps_server_url_changed'));
}
}
export const BASE_URL = getServerUrl();
export const apiClient = axios.create({
baseURL: BASE_URL,
timeout: 0, // No timeout — wait indefinitely until the server responds
headers: {
'Content-Type': 'application/json',
},
});
apiClient.interceptors.request.use((reqConfig) => {
reqConfig.baseURL = getServerUrl();
const token = getApiToken();
if (token) {
reqConfig.headers.set('Authorization', `Bearer ${token}`);
}
return reqConfig;
});
function formatErrorDetail(rawDetail: unknown): string {
if (typeof rawDetail === 'string') return rawDetail;
if (Array.isArray(rawDetail)) {
const msgs = rawDetail
.map((item) => {
if (typeof item === 'string') return item;
if (item && typeof item === 'object') {
const obj = item as { msg?: unknown; loc?: unknown };
const msg = typeof obj.msg === 'string' ? obj.msg : JSON.stringify(item);
const loc = Array.isArray(obj.loc) ? obj.loc.join('.') : '';
return loc ? `${loc}: ${msg}` : msg;
}
return String(item);
})
.filter(Boolean);
if (msgs.length > 0) return msgs.join('; ');
}
if (rawDetail && typeof rawDetail === 'object') {
return JSON.stringify(rawDetail);
}
return '';
}
apiClient.interceptors.response.use(
(response) => response,
(error) => {
const status = error.response?.status;
const detailMsg = formatErrorDetail(error.response?.data?.detail);
const message =
detailMsg ||
error.response?.data?.message ||
error.message ||
'An unexpected error occurred';
const enriched = Object.assign(new Error(message), {
status,
response: error.response,
});
return Promise.reject(enriched);
}
);
function appendWsToken(url: string): string {
const token = getApiToken();
if (!token) return url;
const sep = url.includes('?') ? '&' : '?';
return `${url}${sep}token=${encodeURIComponent(token)}`;
}
// WebSocket URL:
// - User-configured Server URL in localStorage always overrides build-time VITE_WS_URL
export function resolveWsUrl(): string | null {
const customServer =
typeof window !== 'undefined' ? (localStorage.getItem('perps_server_url') || '').trim().replace(/\/+$/, '') : '';
if (customServer) {
const wsProto = customServer.startsWith('https://') ? 'wss://' : 'ws://';
const host = customServer.replace(/^https?:\/\//, '');
return appendWsToken(`${wsProto}${host}/ws/signals`);
}
if (import.meta.env.VITE_WS_URL) {
return appendWsToken(import.meta.env.VITE_WS_URL.trim().replace(/\/+$/, ''));
}
const base = getServerUrl();
if (base) {
const wsProto = base.startsWith('https://') ? 'wss://' : 'ws://';
const host = base.replace(/^https?:\/\//, '');
return appendWsToken(`${wsProto}${host}/ws/signals`);
}
if (typeof window !== 'undefined') {
if (window.location.port === '5173') {
return appendWsToken('ws://127.0.0.1:8000/ws/signals');
}
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
return appendWsToken(`${proto}//${window.location.host}/ws/signals`);
}
return null;
}
export function resolveChartWsUrl(symbol: string, exchange?: string): string | null {
const cleanSym = symbol.toUpperCase().replace(/[/-]/g, '');
const exchQuery = exchange && exchange !== 'auto' ? `?exchange=${encodeURIComponent(exchange)}` : '';
const customServer =
typeof window !== 'undefined' ? (localStorage.getItem('perps_server_url') || '').trim().replace(/\/+$/, '') : '';
if (customServer) {
const wsProto = customServer.startsWith('https://') ? 'wss://' : 'ws://';
const host = customServer.replace(/^https?:\/\//, '');
return `${wsProto}${host}/ws/chart/${cleanSym}${exchQuery}`;
}
if (import.meta.env.VITE_WS_URL) {
const baseWs = import.meta.env.VITE_WS_URL.trim().replace(/\/ws\/signals\/?$/, '').replace(/\/+$/, '');
return `${baseWs}/ws/chart/${cleanSym}${exchQuery}`;
}
const base = getServerUrl();
if (base) {
const wsProto = base.startsWith('https://') ? 'wss://' : 'ws://';
const host = base.replace(/^https?:\/\//, '');
return `${wsProto}${host}/ws/chart/${cleanSym}${exchQuery}`;
}
if (typeof window !== 'undefined') {
if (window.location.port === '5173') {
return `ws://127.0.0.1:8000/ws/chart/${cleanSym}${exchQuery}`;
}
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
return `${proto}//${window.location.host}/ws/chart/${cleanSym}${exchQuery}`;
}
return null;
}
export const WS_URL = resolveWsUrl();