import { Binding , BindingScope , Context } from '@loopback/core' ; import { Request } from '@loopback/rest' ; import debugFactory from 'debug' ; import { APPLICATION_COUNTER , REQUEST_COUNTER , SERVER_COUNTER } from './keys' ; const debug = debugFactory ( 'loopback:example:binding-resolution' ) ; /**
 * Log function interface
 */ export type Logger = typeof console . log ; param currentCtx param binding param logger export function logContexts ( currentCtx , binding , logger = debug ) { const ownerCtx = currentCtx . getOwnerContext ( binding . key ) ; logContext ( 'Owner' , ownerCtx , binding , logger ) ; logContext ( 'Resolution' , currentCtx , binding , logger ) ; } param type param ctx param binding param logger export function logContext ( type , ctx , binding , logger = debug ) { logger ( `[%s%s] ${ type } context: %s` , binding . key , binding . scope === BindingScope . SINGLETON ? '*' : '' , ctx ?. name ) ; } param request param logger export function logRequest ( request , logger = debug ) { logger ( 'Request: %s %s' , request . method , request . originalUrl , request . headers ) ; } export function log ( message , ... args ) { debug ( message , ... args ) ; } param param export function bindingScope ( name , defaultScope = BindingScope . SINGLETON ) { const scopeName = ( process . env . BINDING_SCOPE ?? defaultScope ) . toLowerCase ( ) ; const scopes = [ BindingScope . APPLICATION , BindingScope . SERVER , BindingScope . REQUEST , BindingScope . SINGLETON , BindingScope . TRANSIENT , BindingScope . CONTEXT , ] ; const scope = scopes . find ( s => s . toLowerCase ( ) === scopeName ) ?? BindingScope . TRANSIENT ; debug ( 'Binding scope for "%s" is set to "%s".' , name , scope ) ; return scope ; } export async function count ( ctx , name ) { const keys = [ REQUEST_COUNTER , SERVER_COUNTER , APPLICATION_COUNTER ] ; for ( const key of keys ) { const counter = await ctx . get ( key ) ; counter . inc ( ) ; debug ( '[%s] Counter: %s %d' , name , counter . scope , counter . value ) ; } }