2017-01-16 21:02:11 +00:00
export function execOnce ( fn ) {
let used = false
return ( ... args ) => {
if ( ! used ) {
used = true
fn . apply ( this , args )
}
}
}
2018-10-01 22:55:31 +00:00
export function getLocationOrigin ( ) {
const { protocol , hostname , port } = window . location
return ` ${ protocol } // ${ hostname } ${ port ? ':' + port : '' } `
}
export function getURL ( ) {
const { href } = window . location
const origin = getLocationOrigin ( )
return href . substring ( origin . length )
}
2017-06-19 13:03:02 +00:00
export function getDisplayName ( Component ) {
2018-08-13 18:03:59 +00:00
if ( typeof Component === 'string' ) {
return Component
}
2017-06-19 13:03:02 +00:00
return Component . displayName || Component . name || 'Unknown'
}
2018-01-31 13:12:21 +00:00
export function isResSent ( res ) {
return res . finished || res . headersSent
}
2017-01-20 19:33:46 +00:00
export async function loadGetInitialProps ( Component , ctx ) {
2018-08-09 17:13:44 +00:00
if ( process . env . NODE _ENV !== 'production' ) {
if ( Component . prototype && Component . prototype . getInitialProps ) {
const compName = getDisplayName ( Component )
2018-08-24 10:30:27 +00:00
const message = ` " ${ compName } .getInitialProps()" is defined as an instance method - visit https://err.sh/zeit/next.js/get-initial-props-as-an-instance-method for more information. `
2018-08-09 17:13:44 +00:00
throw new Error ( message )
}
}
2017-01-20 19:33:46 +00:00
if ( ! Component . getInitialProps ) return { }
const props = await Component . getInitialProps ( ctx )
2018-01-31 13:12:21 +00:00
if ( ctx . res && isResSent ( ctx . res ) ) {
return props
}
if ( ! props ) {
2017-06-19 13:03:02 +00:00
const compName = getDisplayName ( Component )
2017-01-20 19:33:46 +00:00
const message = ` " ${ compName } .getInitialProps()" should resolve to an object. But found " ${ props } " instead. `
throw new Error ( message )
}
2018-01-31 13:12:21 +00:00
2017-01-20 19:33:46 +00:00
return props
}