-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
custom-inject-resolve.ts
60 lines (52 loc) · 1.49 KB
/
custom-inject-resolve.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright IBM Corp. 2019. All Rights Reserved.
// Node module: @loopback/example-context
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {
BindingKey,
Context,
inject,
Injection,
ResolutionSession,
ResolverFunction,
} from '@loopback/context';
/**
* Custom resolver function for bindings
* @param ctx The current context
* @param injection Metadata about the injection
* @param session Current resolution session
*/
const resolve: ResolverFunction = (
ctx: Context,
injection: Readonly<Injection>,
session: ResolutionSession,
) => {
console.log('Context: %s Binding: %s', ctx.name, session.currentBinding!.key);
const targetName = ResolutionSession.describeInjection(injection).targetName;
console.log('Injection: %s', targetName);
return injection.member === 'prefix' ? new Date().toISOString() : 'John';
};
/**
* A class with dependency injection
*/
class Greeter {
constructor(@inject('', {}, resolve) private name: string) {}
@inject('', {}, resolve)
prefix: string = '';
hello() {
return `[${this.prefix}] Hello, ${this.name}`;
}
}
const GREETER = BindingKey.create<Greeter>('greeter');
export async function main() {
const ctx = new Context('invocation-context');
ctx.bind(GREETER).toClass(Greeter);
const greeter = await ctx.get(GREETER);
console.log(greeter.hello());
}
if (require.main === module) {
main().catch(err => {
console.error(err);
process.exit(1);
});
}