-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
configuration-injection.ts
54 lines (46 loc) · 1.24 KB
/
configuration-injection.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
// 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 {config, Context} from '@loopback/context';
/**
* Configuration for greeters
*/
type GreeterConfig = {
prefix?: string;
includeDate?: boolean;
};
/**
* A greeter service
*/
class Greeter {
constructor(
/**
* Inject configuration for this bound instance
*/
@config() private settings: GreeterConfig = {},
) {}
greet(name: string) {
const prefix = this.settings.prefix ? `${this.settings.prefix}` : '';
const date = this.settings.includeDate
? `[${new Date().toISOString()}]`
: '';
return `${date} ${prefix}: Hello, ${name}`;
}
}
export async function main() {
const ctx = new Context();
// Configure `greeter` with `{prefix: '>>>', includeDate: true}`
ctx
.configure<GreeterConfig>('greeter')
.to({prefix: '>>>', includeDate: true});
ctx.bind('greeter').toClass(Greeter);
const greeter = await ctx.get<Greeter>('greeter');
console.log(greeter.greet('Ray'));
}
if (require.main === module) {
main().catch(err => {
console.error(err);
process.exit(1);
});
}