import { BindingKey , Context , ContextView , filterByTag , Getter , inject , invokeMethod , } from '@loopback/context' ; /**
 * A strongly-typed binding key for current date
 */ const CURRENT_DATE = BindingKey . create < Date > ( 'currentDate' ) ; /**
 * A strongly-typed binding key for `GreetingService`
 */ const GREETING_SERVICE = BindingKey . create < GreetingService > ( 'services.GreetingService' ) ; /**
 * A factory function to return the current date
 */ const getCurrentDate = ( ) => new Date ( ) ; interface Greeter { language : string ; greet ( name ) : string ; } class ChineseGreeter implements Greeter { language = 'zh' ; greet ( name ) { return `你好，${ name }！` ; } } class EnglishGreeter implements Greeter { language = 'en' ; greet ( name ) { return `Hello, ${ name }!` ; } } /**
 * A class with dependency injection
 */ class GreetingService { constructor ( @ inject . view ( filterByTag ( 'greeter' ) ) private greetersView ) { } @ inject . getter ( CURRENT_DATE ) private now : Getter < Date > ; async greet ( @ inject ( 'currentLanguage' ) language , @ inject ( 'currentUser' ) userName ) { const date = await this . now ( ) ; const greeters = await this . greetersView . values ( ) ; for ( const greeter of greeters ) { if ( greeter . language === language ) { const msg = greeter . greet ( userName ) ; return `[${ date . toISOString ( ) }] (${ language }) ${ msg }` ; } } return `[${ date . toISOString ( ) }] Hello, ${ userName }!` ; } } export async function main ( ) { const ctx = new Context ( 'request' ) ; ctx . bind ( GREETING_SERVICE ) . toClass ( GreetingService ) ; ctx . bind ( CURRENT_DATE ) . toDynamicValue ( getCurrentDate ) ; ctx . bind ( 'currentUser' ) . to ( 'John' ) ; ctx . bind ( 'currentLanguage' ) . to ( 'zh' ) ; ctx . bind ( 'greeters.EnglishGreeter' ) . toClass ( EnglishGreeter ) . tag ( 'greeter' ) ; const greetingService = await ctx . get ( GREETING_SERVICE ) ; let greeting = await greetingService . greet ( 'en' , 'Jane' ) ; console . log ( greeting ) ; greeting = await invokeMethod ( greetingService , 'greet' , ctx ) ; console . log ( greeting ) ; ctx . bind ( 'greeters.ChineseGreeter' ) . toClass ( ChineseGreeter ) . tag ( 'greeter' ) ; greeting = await invokeMethod ( greetingService , 'greet' , ctx ) ; console . log ( greeting ) ; ctx . bind ( 'currentLanguage' ) . to ( 'en' ) ; ctx . bind ( 'currentUser' ) . to ( 'Jane' ) ; greeting = await invokeMethod ( greetingService , 'greet' , ctx ) ; console . log ( greeting ) ; } if ( require . main === module ) { main ( ) . catch ( err => { console . error ( err ) ; process . exit ( 1 ) ; } ) ; }