import { getLogger } from './logger' ; function isPromise ( e ) { return ! ! e && typeof e . then === 'function' ; } const logger = getLogger ( 'profiler' ) ; function printCost ( start , end , target , method ) { logger . info ( `${ target }, ${ method }, ${ end . getTime ( ) - start . getTime ( ) } ms` ) ; } export function profiler ( enabled = true ) { return ( target , name , descriptor ) : void => { if ( enabled && ! ! descriptor && typeof descriptor . value === 'function' ) { const orig = descriptor . value ; descriptor . value = function ( ... args ) : any { const start = new Date ( ) ; const res = orig . bind ( this ) ( ... args ) ; if ( isPromise ( res ) ) { res . then ( ( _ ) => { printCost ( start , new Date ( ) , target . constructor . name , name ) ; return _ ; } , ( err ) => { printCost ( start , new Date ( ) , target . constructor . name , name ) ; throw err ; } ) ; } else { printCost ( start , new Date ( ) , target . constructor . name , name ) ; } return res ; } ; } } ; } export const profilerWrap = ( method , target , name ) : any => ( ... args ) => { const start = new Date ( ) ; const res = method ( ... args ) ; if ( isPromise ( res ) ) { res . then ( ( _ ) => { printCost ( start , new Date ( ) , target , name ) ; return _ ; } , ( err ) => { printCost ( start , new Date ( ) , target , name ) ; throw err ; } ) ; } else { printCost ( start , new Date ( ) , target , name ) ; } return res ; } ;