UNPKG

2.55 kBPlain TextView Raw
1// Copyright IBM Corp. and LoopBack contributors 2019,2020. All Rights Reserved.
2// Node module: @loopback/context
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6import {BindingAddress, BindingKey} from './binding-key';
7import {Context} from './context';
8import {ResolutionOptions} from './resolution-session';
9import {ValueOrPromise} from './value-promise';
10
11/**
12 * Resolver for configuration of bindings. It's responsible for finding
13 * corresponding configuration for a given binding key.
14 *
15 * By default, `undefined` is expected if no configuration is provided. The
16 * behavior can be overridden by setting `optional` to `false` in resolution
17 * options.
18 */
19export interface ConfigurationResolver {
20 /**
21 * Resolve config for the binding key
22 *
23 * @param key - Binding key
24 * @param propertyPath - Property path for the option. For example, `x.y`
25 * requests for `<config>.x.y`. If not set, the `config` object will be
26 * returned.
27 * @param resolutionOptions - Options for the resolution.
28 * - optional: if not set or set to `true`, `undefined` will be returned if
29 * no corresponding value is found. Otherwise, an error will be thrown.
30 */
31 getConfigAsValueOrPromise<ConfigValueType>(
32 key: BindingAddress<unknown>,
33 propertyPath?: string,
34 resolutionOptions?: ResolutionOptions,
35 ): ValueOrPromise<ConfigValueType | undefined>;
36}
37
38/**
39 * Resolver for configurations of bindings
40 */
41export class DefaultConfigurationResolver implements ConfigurationResolver {
42 constructor(public readonly context: Context) {}
43
44 getConfigAsValueOrPromise<ConfigValueType>(
45 key: BindingAddress<unknown>,
46 propertyPath?: string,
47 resolutionOptions?: ResolutionOptions,
48 ): ValueOrPromise<ConfigValueType | undefined> {
49 propertyPath = propertyPath ?? '';
50 const configKey = configBindingKeyFor(key, propertyPath);
51
52 const options: ResolutionOptions = Object.assign(
53 {optional: true},
54 resolutionOptions,
55 );
56 return this.context.getValueOrPromise<ConfigValueType>(configKey, options);
57 }
58}
59
60/**
61 * Create binding key for configuration of the binding
62 * @param key - Binding key for the target binding
63 * @param propertyPath - Property path for the configuration
64 */
65export function configBindingKeyFor<ConfigValueType = unknown>(
66 key: BindingAddress,
67 propertyPath?: string,
68) {
69 return BindingKey.create<ConfigValueType>(
70 BindingKey.buildKeyForConfig<ConfigValueType>(key).toString(),
71 propertyPath,
72 );
73}