Skip to content

Commit b41546e

Browse files
#76 Added API for ES6+ projects
1 parent 5334365 commit b41546e

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

src/lib/decorators.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,26 @@
1-
import { IInjectionMd } from './interfaces';
1+
import { IInjectionMd, ProviderToken } from './interfaces';
22
import { INJECTABLE_MD_KEY, INJECTIONS_MD_KEY } from './metadata/keys';
33
import { IMetadataAnnotator } from './metadata/metadata-annotator.interface';
44
import { AnnotatorProvider } from './metadata/index';
55

66
const MetadataAnnotator: IMetadataAnnotator = AnnotatorProvider.get();
77

8-
export function Injectable() {
8+
export function Injectable(injections?: ProviderToken[]) {
99
return (target: object) => {
1010
MetadataAnnotator.defineMetadata(INJECTABLE_MD_KEY, true, target);
11+
12+
if (injections && Array.isArray(injections)) {
13+
const injectionMd: IInjectionMd[] = MetadataAnnotator.getMetadata(INJECTIONS_MD_KEY, target) || [];
14+
15+
injections.forEach((injectionToken, injectionIndex) => {
16+
injectionMd.push({
17+
token: injectionToken,
18+
parameterIndex: injectionIndex
19+
});
20+
});
21+
22+
MetadataAnnotator.defineMetadata(INJECTIONS_MD_KEY, injectionMd, target);
23+
}
1124
};
1225
}
1326

src/tests/decorators.spec.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,28 @@ describe('Decorators', () => {
6767
const throwableFunc = () => container.resolve(1);
6868
expect(throwableFunc).to.throw();
6969
});
70+
71+
it('should resolve an instance with all the dependencies specified in Injectable decorator', () => {
72+
@Injectable()
73+
class A {}
74+
75+
@Injectable(['IA'])
76+
class B {
77+
a: A;
78+
constructor(a: A) {
79+
this.a = a;
80+
}
81+
}
82+
83+
container.register([
84+
{ token: 'IA', useClass: A },
85+
{ token: 'IB', useClass: B }
86+
]);
87+
88+
const instance = container.resolve('IB');
89+
90+
expect(instance.a).to.be.instanceOf(A);
91+
});
7092
});
7193

7294
describe('@Injectable()', () => {

0 commit comments

Comments
 (0)