import { BindingKey , Context , inject , Provider } from '@loopback/context' ; /**
 * A strongly-typed binding key for current date
 */ const CURRENT_DATE = BindingKey . create < Date > ( 'currentDate' ) ; /**
 * A strongly-typed binding key for `Greeter`
 */ const GREETER = BindingKey . create < Greeter > ( 'greeter' ) ; /**
 * A factory function to return the current date
 */ const getCurrentDate = ( ) => new Date ( ) ; /**
 * A class with dependency injection
 */ class Greeter { constructor ( @ inject ( 'currentUser' ) private userName ) { } @ inject ( CURRENT_DATE ) private created : Date ; @ inject ( 'requestId' ) private requestId : string ; hello ( ) { return `[${ this . created . toISOString ( ) }] (${ this . requestId }) Hello, ${ this . userName }` ; } } /**
 * A provider is similar as the factory function but it requires dependency
 * injection. As a result, it's declared as a class with `@inject.*` decorations
 * applied.
 */ class RequestIdProvider implements Provider < string > { static ids : Map < string , number > = new Map ( ) ; constructor ( @ inject ( 'url' ) private url ) { } value ( ) { let id = RequestIdProvider . ids . get ( this . url ) ; if ( id == null ) { id = 1 ; } else { id ++ ; } RequestIdProvider . ids . set ( this . url , id ) ; return `${ this . url }#${ id }` ; } } export async function main ( ) { const ctx = new Context ( 'request' ) ; ctx . bind ( 'currentUser' ) . to ( 'John' ) ; ctx . bind ( 'url' ) . to ( '/greet' ) ; ctx . bind ( CURRENT_DATE ) . toDynamicValue ( getCurrentDate ) ; ctx . bind ( GREETER ) . toClass ( Greeter ) ; ctx . bind ( 'requestId' ) . toProvider ( RequestIdProvider ) ; ctx . bind ( 'hello' ) . toAlias ( GREETER ) ; let greeter = await ctx . get ( GREETER ) ; console . log ( greeter . hello ( ) ) ; greeter = await ctx . get < Greeter > ( 'hello' ) ; console . log ( greeter . hello ( ) ) ; } if ( require . main === module ) { main ( ) . catch ( err => { console . error ( err ) ; process . exit ( 1 ) ; } ) ; }