import { BindingKey , Context , inject } from '@loopback/context' ; const CURRENT_USER = BindingKey . create < string > ( 'currentUser' ) ; /**
 * A class with dependency injection
 */ class Greeter { param userName constructor ( @ inject ( CURRENT_USER ) private userName ) { } hello ( ) { return `Hello, ${ this . userName }` ; } } /**
 * A strongly-typed binding key for `Greeter`
 */ const GREETER = BindingKey . create < Greeter > ( 'greeter' ) ; async function greetWithSyncUser ( ctx ) { ctx . bind ( CURRENT_USER ) . to ( 'John (sync)' ) ; let greeter = ctx . getSync ( GREETER ) ; console . log ( '%s' , greeter . hello ( ) ) ; greeter = await ctx . get ( GREETER ) ; console . log ( '%s' , greeter . hello ( ) ) ; return greeter ; } async function greetWithAsyncUser ( ctx ) { ctx . bind ( CURRENT_USER ) . toDynamicValue ( ( ) => Promise . resolve ( 'Jane (async)' ) ) ; let greeter = await ctx . get ( GREETER ) ; console . log ( '%s' , greeter . hello ( ) ) ; try { greeter = ctx . getSync ( GREETER ) ; console . log ( greeter . hello ( ) ) ; } catch ( err ) { console . log ( 'Expect to fail with error: %s' , err . message ) ; } } export async function main ( ) { const ctx = new Context ( 'request' ) ; ctx . bind ( GREETER ) . toClass ( Greeter ) ; await greetWithSyncUser ( ctx ) ; await greetWithAsyncUser ( ctx ) ; } if ( require . main === module ) { main ( ) . catch ( err => { console . error ( err ) ; process . exit ( 1 ) ; } ) ; }