import { configure , axiosAll , defaultSettings , isFunction } from './common' ; export const feedRequests = async ( context , ssrHtml , maxRequests = context . settings . maxRequests ) => { const { settings , collection : { ssrConfigs , cacheKeys } , } = context ; const { cache , renderSSR , debug } = settings ; if ( ! ssrConfigs . length ) { if ( debug ) { console . log ( '[ReactUseApi][Requests Count] =' , cacheKeys . size ) ; console . log ( '[ReactUseApi][Executed Times] =' , settings . maxRequests - maxRequests ) ; } cacheKeys . clear ( ) ; return ssrHtml ; } debug && console . log ( '[ReactUseApi][Collecting Requests]' ) ; if ( maxRequests === 0 ) { console . error ( '[ReactUseApi][ERROR] - Maximum executing times while fetching axios requests' , '[congis]:' , ssrConfigs , '[Executed Times]:' , settings . maxRequests - maxRequests ) ; cacheKeys . clear ( ) ; return ssrHtml ; } const { config , cacheKey } = ssrConfigs [ 0 ] ; const cacheData = cache . get ( cacheKey ) ; if ( ! cacheData ) { try { debug && console . log ( '[ReactUseApi][Fetch]' , cacheKey ) ; const response = await axiosAll ( context , config ) ; cache . set ( cacheKey , { response , } ) ; } catch ( error ) { if ( error ?. response ?. data ) { cache . set ( cacheKey , { error : error . response , } ) ; } else { throw error ; } } } ssrConfigs . length = 0 ; ssrHtml = renderSSR ( ) ; return await feedRequests ( context , ssrHtml , -- maxRequests ) ; } ; export const injectSSRHtml = async ( context , renderSSR ? , postProcess ? ) => { context = configure ( context , true ) ; const { settings } = context ; settings . renderSSR = renderSSR || settings . renderSSR ; const { cache , useCacheData , clientCacheVar , shouldUseApiCache } = settings ; cache . reset ( ) ; let ssrHtml = settings . renderSSR ( ) ; ssrHtml = await exports . feedRequests ( context , ssrHtml ) ; if ( useCacheData ) { const cacheJson = cache . dump ( ) . filter ( ( { k : cacheKey } ) => { let config ; try { config = JSON . parse ( cacheKey ) ; } catch ( e ) { config = { } ; } return shouldUseApiCache ( config , cacheKey ) !== false ; } ) ; const apiCacheScript = Object . keys ( cacheJson ) ? `<script>window.${ clientCacheVar } = ${ JSON . stringify ( cacheJson ) . replace ( /</g , '\\u003c' ) }</script>` : '' ; return isFunction ( postProcess ) ? postProcess ( ssrHtml , apiCacheScript ) : ssrHtml + apiCacheScript ; } return ssrHtml ; } ; export const loadApiCache = ( context = { settings : defaultSettings } ) => { const { settings } = context ; const { clientCacheVar } = settings ; const data = window [ clientCacheVar ] ; if ( Array . isArray ( data ) ) { settings . cache . load ( data ) ; delete window [ clientCacheVar ] ; } } ;