import { onServerPrefetch , watch , computed , ref } from '@vue/composition-api' ; import type { Ref } from '@vue/composition-api' ; import { joinURL } from 'ufo' ; import { ssrRef } from './ssr-ref' ; import { globalContext , staticPath , publicPath as _publicPath , } from '@nuxtjs/composition-api/dist/runtime/globals' ; const staticCache = { } ; function writeFile ( key , value ) { if ( process . client || ! process . static ) return ; const { writeFileSync } = process . client ? '' : require ( 'fs' ) ; const { join } = process . client ? '' : require ( 'upath' ) ; try { writeFileSync ( join ( staticPath , `${ key }.json` ) , value ) ; } catch ( e ) { console . log ( e ) ; } } param factory param param param keyBase example export const useStatic = < T > ( factory , param = ref ( '' ) , keyBase ) : Ref < T | null > => { const key = computed ( ( ) => `${ keyBase }-${ param . value }` ) ; const result = ssrRef < T | null > ( null , key . value ) ; if ( result . value ) staticCache [ key . value ] = result . value ; if ( process . client ) { const publicPath = ( window as any ) [ globalContext ] . $config ?. app ?. cdnURL || _publicPath ; const onFailure = ( ) => factory ( param . value , key . value ) . then ( r => { staticCache [ key . value ] = r ; result . value = r ; return ; } ) ; watch ( key , key => { if ( key in staticCache ) { result . value = staticCache [ key ] ; return ; } if ( ! process . static ) onFailure ( ) ; else fetch ( joinURL ( publicPath , `${ key }.json` ) ) . then ( response => { if ( ! response . ok ) throw new Error ( 'Response invalid.' ) ; return response . json ( ) ; } ) . then ( json => { staticCache [ key ] = json ; result . value = json ; } ) . catch ( onFailure ) ; } , { immediate : true , } ) ; } else { if ( key . value in staticCache ) { result . value = staticCache [ key . value ] ; return result as Ref < T | null > ; } onServerPrefetch ( async ( ) => { const [ _key , _param ] = [ key . value , param . value ] ; result . value = await factory ( _param , _key ) ; staticCache [ _key ] = result . value ; writeFile ( _key , JSON . stringify ( result . value ) ) ; } ) ; } return result as Ref < T | null > ; } ;