Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions docs/site/Binding.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,56 @@ const serverBinding = new Binding<RestServer>('servers.RestServer1');
serverBinding.apply(serverTemplate);
```

### Configure binding attributes for a class

Classes can be discovered and bound to the application context during `boot`. In
addition to conventions, it's often desirable to allow certain binding
attributes, such as scope and tags, to be specified as metadata for the class.
When the class is bound, these attributes are honored to create a binding. You
can use `@bind` decorator to configure how to bind a class.

```ts
import {bind, BindingScope} from '@loopback/context';

// @bind() accepts scope and tags
@bind({
scope: BindingScope.SINGLETON,
tags: ['service'],
})
export class MyService {}

// @binding.provider is a shortcut for a provider class
@bind.provider({
tags: {
key: 'my-date-provider',
},
})
export class MyDateProvider implements Provider<Date> {
value() {
return new Date();
}
}

@bind({
tags: ['controller', {name: 'my-controller'}],
})
export class MyController {}

// @bind() can take one or more binding template functions
@bind(binding => binding.tag('controller', {name: 'your-controller'})
export class YourController {}
```

Then a binding can be created by inspecting the class,

```ts
import {createBindingFromClass} from '@loopback/context';

const ctx = new Context();
const binding = createBindingFromClass(MyService);
ctx.add(binding);
```

### Encoding value types in binding keys

String keys for bindings do not help enforce the value type. Consider the
Expand Down
1 change: 1 addition & 0 deletions packages/context/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"src/index.ts",
"src/inject.ts",
"src/value-promise.ts",
"src/bind-decorator.ts",
"src/provider.ts",
"src/resolution-session.ts",
"src/resolver.ts"
Expand Down
105 changes: 105 additions & 0 deletions packages/context/src/binding-decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/context
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {ClassDecoratorFactory} from '@loopback/metadata';
import {
asBindingTemplate,
asProvider,
BindingMetadata,
BindingSpec,
BINDING_METADATA_KEY,
isProviderClass,
asClassOrProvider,
removeNameAndKeyTags,
} from './binding-inspector';
import {Provider} from './provider';
import {Constructor} from './value-promise';

/**
* Decorator factory for `@bind`
*/
class BindDecoratorFactory extends ClassDecoratorFactory<BindingMetadata> {
mergeWithInherited(inherited: BindingMetadata, target: Function) {
if (inherited) {
return {
templates: [
...inherited.templates,
removeNameAndKeyTags,
...this.spec.templates,
],
target: this.spec.target,
};
} else {
this.withTarget(this.spec, target);
return this.spec;
}
}

withTarget(spec: BindingMetadata, target: Function) {
spec.target = target as Constructor<unknown>;
return spec;
}
}

/**
* Decorate a class with binding configuration
*
* @example
* ```ts
* @bind((binding) => {binding.inScope(BindingScope.SINGLETON).tag('controller')}
* )
* export class MyController {
* }
* ```
*
* @param specs A list of binding scope/tags or template functions to
* configure the binding
*/
export function bind(...specs: BindingSpec[]): ClassDecorator {
const templateFunctions = specs.map(t => {
if (typeof t === 'function') {
return t;
} else {
return asBindingTemplate(t);
}
});

return (target: Function) => {
const cls = target as Constructor<unknown>;
const spec: BindingMetadata = {
templates: [asClassOrProvider(cls), ...templateFunctions],
target: cls,
};

const decorator = BindDecoratorFactory.createDecorator(
BINDING_METADATA_KEY,
spec,
);
decorator(target);
};
}

export namespace bind {
/**
* `@bind.provider` to denote a provider class
*
* A list of binding scope/tags or template functions to configure the binding
*/
export function provider(
...specs: BindingSpec[]
): ((target: Constructor<Provider<unknown>>) => void) {
return (target: Constructor<Provider<unknown>>) => {
if (!isProviderClass(target)) {
throw new Error(`Target ${target} is not a Provider`);
}
bind(
// Set up the default for providers
asProvider(target),
// Call other template functions
...specs,
)(target);
};
}
}
Loading