-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
parameterized-decoration.ts
71 lines (60 loc) · 1.76 KB
/
parameterized-decoration.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
61
62
63
64
65
66
67
68
69
70
71
// 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 {
bind,
BindingAddress,
BindingTag,
Constructor,
Context,
createBindingFromClass,
inject,
} from '@loopback/context';
/**
* Interface for `Greeter`
*/
interface Greeter {
hello(): string;
}
/**
* A function to create a new class with parameterized decorations
* @param bindingKeyForName Binding key for current user
* @param tags Additional binding tags
*/
function createClassWithDecoration(
bindingKeyForName: BindingAddress<string>,
...tags: BindingTag[]
): Constructor<Greeter> {
@bind({tags})
class GreeterTemplate implements Greeter {
constructor(@inject(bindingKeyForName) private userName: string) {}
hello() {
return `Hello, ${this.userName}`;
}
}
return GreeterTemplate;
}
export async function main() {
const ctx = new Context();
ctx.bind('name1').to('John');
ctx.bind('name2').to('Jane');
const class1 = createClassWithDecoration('name1', {tags: {prefix: '1'}});
const binding1 = createBindingFromClass(class1, {key: 'greeter1'});
ctx.add(binding1);
console.log('1:', binding1.tagMap);
const class2 = createClassWithDecoration('name2', {tags: {prefix: '2'}});
const binding2 = createBindingFromClass(class2, {key: 'greeter2'});
ctx.add(binding2);
console.log('2:', binding2.tagMap);
const greeting1 = await ctx.get<Greeter>('greeter1');
console.log('1: %s', greeting1.hello());
const greeting2 = await ctx.get<Greeter>('greeter2');
console.log('2: %s', greeting2.hello());
}
if (require.main === module) {
main().catch(err => {
console.error(err);
process.exit(1);
});
}