@@ -6,34 +6,62 @@ import { supabase } from "../../lib/supabaseClient";
66const API_BASE = process . env . NEXT_PUBLIC_API_URL || "https://edeziav2.onrender.com/api/v1" ;
77
88const safeFetch = async ( url : string , options : RequestInit = { } ) : Promise < Response > => {
9- if ( url . includes ( "," ) ) {
10- const parts = url . split ( "," ) ;
11- const firstBase = parts [ 0 ] ;
12- const rest = parts . slice ( 1 ) . join ( "," ) ;
13-
14- // Resolve path from secondary base dynamically
9+ const controller = new AbortController ( ) ;
10+ const id = setTimeout ( ( ) => controller . abort ( ) , 6000 ) ; // 6 seconds timeout
11+
12+ const fetchOptions = {
13+ ...options ,
14+ signal : controller . signal
15+ } ;
16+
17+ try {
18+ if ( url . includes ( "," ) ) {
19+ const parts = url . split ( "," ) ;
20+ const firstBase = parts [ 0 ] ;
21+ const rest = parts . slice ( 1 ) . join ( "," ) ;
22+
23+ // Resolve path from secondary base dynamically
1524 const secondBase = "https://edeziav2.onrender.com/api/v1" ;
16- let path = "" ;
17- if ( rest . startsWith ( secondBase ) ) {
18- path = rest . substring ( secondBase . length ) ;
19- } else {
20- const idx = rest . indexOf ( "/api/v1" ) ;
21- if ( idx !== - 1 ) {
22- path = rest . substring ( idx + "/api/v1" . length ) ;
25+ let path = "" ;
26+ if ( rest . startsWith ( secondBase ) ) {
27+ path = rest . substring ( secondBase . length ) ;
28+ } else {
29+ const idx = rest . indexOf ( "/api/v1" ) ;
30+ if ( idx !== - 1 ) {
31+ path = rest . substring ( idx + "/api/v1" . length ) ;
32+ }
33+ }
34+
35+ const url1 = `${ firstBase } ${ path } ` ;
36+ const url2 = rest ;
37+
38+ try {
39+ const res = await fetch ( url1 , fetchOptions ) ;
40+ clearTimeout ( id ) ;
41+ return res ;
42+ } catch ( err ) {
43+ console . warn ( `Local API offline at ${ url1 } , falling back to remote production at ${ url2 } ` , err ) ;
44+
45+ // Reset timeout for fallback fetch
46+ const fallbackController = new AbortController ( ) ;
47+ const fallbackId = setTimeout ( ( ) => fallbackController . abort ( ) , 6000 ) ;
48+ try {
49+ const res = await fetch ( url2 , { ...options , signal : fallbackController . signal } ) ;
50+ clearTimeout ( fallbackId ) ;
51+ return res ;
52+ } catch ( fallbackErr ) {
53+ clearTimeout ( fallbackId ) ;
54+ throw fallbackErr ;
55+ }
2356 }
2457 }
25-
26- const url1 = `${ firstBase } ${ path } ` ;
27- const url2 = rest ;
28-
29- try {
30- return await fetch ( url1 , options ) ;
31- } catch ( err ) {
32- console . warn ( `Local API offline at ${ url1 } , falling back to remote production at ${ url2 } ` , err ) ;
33- return await fetch ( url2 , options ) ;
34- }
58+ const res = await fetch ( url , fetchOptions ) ;
59+ clearTimeout ( id ) ;
60+ return res ;
61+ } catch ( error ) {
62+ clearTimeout ( id ) ;
63+ throw error ;
3564 }
36- return fetch ( url , options ) ;
3765} ;
3866
3967interface User {
0 commit comments