import React from 'react' ; import dns from 'dns' ; const checkExternalDependency = ( url ) => new Promise ( ( resolve , reject ) => { dns . lookup ( url , ( err ) => { if ( err ) reject ( false ) ; resolve ( true ) ; } ) ; } ) ; export const withHealthchecks = ( externalEndpointDependencies ) => ( Component ) => { const NewComponent = ( props ) => < Component { ... props } / > ; NewComponent . getInitialProps = async ( context ) => { const ctx = context . ctx ?? context ; if ( ctx . req ?. url === '/readiness' ) { const externalDnsRequests = externalEndpointDependencies . map ( ( externalUrl ) => { const url = new URL ( externalUrl ) ; return checkExternalDependency ( url . hostname ) ; } ) ; const status = await Promise . all ( externalDnsRequests ) . then ( ( ) => 200 ) . catch ( ( ) => 500 ) ; ctx . res . statusCode = status ; ctx . res . end ( '' ) ; return null ; } if ( ctx . req ?. url === '/liveness' ) { ctx . res . statusCode = 200 ; ctx . res . end ( '' ) ; return null ; } return Component . getInitialProps ( context ) ; } ; return NewComponent ; } ;