11import { DEPLOYED_WEB_URL } from "common/envs/constants" ;
22
3+ const buildIdKey = 'vercel-buildId' ;
4+
35export const getBuildId = async ( ) => {
46 const res = await fetch ( `${ DEPLOYED_WEB_URL } /api/build-id` )
57 if ( ! res . ok ) throw new Error ( 'Failed to fetch build manifest' )
68 const data = await res . json ( )
7- return data . buildId
9+ const buildId = data . buildId ;
10+ if ( ! buildId ) throw new Error ( 'No buildId found in build manifest' )
11+ localStorage . setItem ( buildIdKey , buildId )
12+ return buildId
813}
914
1015export const getPageData = async ( route = '/' ) => {
11- const buildId = await getBuildId ( )
12- const cleanRoute = route . startsWith ( '/' ) ? route . slice ( 1 ) : route
13- const url = `${ DEPLOYED_WEB_URL } /api/proxy-data?path=${ buildId } /${ cleanRoute || 'index' } .json`
14- console . log ( 'Fetching data from:' , url )
15- const res = await fetch ( url , { cache : 'force-cache' } ) as any
16- if ( ! res . ok ) throw new Error ( `Failed to fetch data for ${ route } ` )
17- const result = await res . json ( ) as any
16+ async function pull ( buildId : string | undefined | null ) {
17+ if ( ! buildId ) {
18+ throw new Error ( 'No buildId found' )
19+ }
20+ const cleanRoute = route . startsWith ( '/' ) ? route . slice ( 1 ) : route
21+ const url = `${ DEPLOYED_WEB_URL } /api/proxy-data?path=${ buildId } /${ cleanRoute || 'index' } .json`
22+ console . log ( 'Fetching data from:' , url )
23+ const res = await fetch ( url , {
24+ cache : 'force-cache' ,
25+ } )
26+
27+ if ( ! res . ok ) {
28+ throw new Error ( `Failed to fetch data for ${ route } : ${ res . status } ${ res . statusText } ` )
29+ }
30+ return res
31+ }
32+
33+ let buildId = localStorage . getItem ( buildIdKey )
34+ if ( ! buildId ) buildId = await getBuildId ( )
35+
36+ let res : Response
37+ try {
38+ res = await pull ( buildId )
39+ } catch ( error : any ) {
40+ if ( error ?. message ?. includes ( '404' ) ) {
41+ console . error ( 'Build ID outdated, loading new one:' , error . message )
42+ buildId = await getBuildId ( )
43+ res = await pull ( buildId )
44+ } else {
45+ throw error
46+ }
47+ }
48+
49+ const result = await res . json ( )
1850 console . log ( 'Fetched Page data:' , result )
1951 return result . pageProps
2052}
0 commit comments