import { Middleware , ResolverContext } from './Middleware' ; import { ExecutionContext } from '../execution/ExecutionContext' ; export type FieldTimerTimeUnit = 'milli' | 'micro' | 'nano' ; export class ResolverTimer implements Middleware < Map < string , number > , number , mixed > { constructor ( private logger , private timeUnit = 'milli' ) { } public beforeQuery ( ) { const contextmap = new Map ( ) ; contextmap . set ( '__START__' , this . getTime ( ) ) ; return contextmap ; } public beforeField ( ) { return this . getTime ( ) ; } public afterField ( mVal , fValue , _value , _eCtx , mCtx ) { mVal . set ( `${ mCtx . info . parentType . name }.${ mCtx . info . fieldName }` , this . getTime ( ) - fValue ) ; return ; } public afterQuery ( mVal ) { const totalRuntime = this . getTime ( ) - ( mVal . get ( '__START__' ) as number ) ; mVal . delete ( '__START__' ) ; this . logger ( totalRuntime , mVal ) ; } private getTime ( ) { const hrTime = process . hrtime ( ) ; switch ( this . timeUnit ) { case 'milli' : return hrTime [ 0 ] * 1000 + hrTime [ 1 ] / 1000000 ; case 'micro' : return hrTime [ 0 ] * 1000000 + hrTime [ 1 ] / 1000 ; case 'nano' : return hrTime [ 0 ] * 1000000000 + hrTime [ 1 ] ; default : return hrTime [ 0 ] * 1000000000 + hrTime [ 1 ] ; } } }