import { Context , ContextView , filterByTag , isPromiseLike , resolveList , resolveMap , transformValueOrPromise , ValueOrPromise , } from '@loopback/context' ; /**
 * Interface for greeters
 */ interface Greeter { language : string ; param name returns greet ( name ) : ValueOrPromise < string > ; } class ChineseGreeter implements Greeter { language = 'zh' ; greet ( name ) { return `[value] 你好，${ name }！` ; } } class EnglishGreeter implements Greeter { language = 'en' ; greet ( name ) { return `[value] Hello, ${ name }!` ; } } class AsyncChineseGreeter implements Greeter { language = 'zh' ; param name greet ( name ) { return new Promise < string > ( resolve => setImmediate ( ( ) => { resolve ( `[promise] 你好，${ name }！` ) ; } ) ) ; } } export async function main ( ) { const ctx = new Context ( 'app' ) ; ctx . bind ( 'greeters.EnglishGreeter' ) . toClass ( EnglishGreeter ) . tag ( 'greeter' ) ; ctx . bind ( 'greeters.ChineseGreeter' ) . toClass ( ChineseGreeter ) . tag ( 'greeter' ) ; const greetersView = ctx . createView < Greeter > ( filterByTag ( 'greeter' ) ) ; await greetFromAll ( greetersView ) ; ctx . bind ( 'greeters.ChineseGreeter' ) . toClass ( AsyncChineseGreeter ) . tag ( 'greeter' ) ; await greetFromAll ( greetersView ) ; } param greetersView async function greetFromAll ( greetersView ) { const greeters = await greetersView . values ( ) ; const greetings = resolveList ( greeters , greeter => { return greeter . greet ( 'John' ) ; } ) ; if ( isPromiseLike ( greetings ) ) { console . log ( 'async:' , await greetings ) ; } else { console . log ( 'sync:' , greetings ) ; } const greeterMap = { } ; greeters . filter ( greeter => ( greeterMap [ greeter . language ] = greeter ) ) ; const greetingsByLanguage = resolveMap ( greeterMap , greeter => greeter . greet ( 'Jane' ) ) ; await transformValueOrPromise ( greetingsByLanguage , console . log ) ; } if ( require . main === module ) { main ( ) . catch ( err => { console . error ( err ) ; process . exit ( 1 ) ; } ) ; }