Skip to content

Commit b8305bf

Browse files
committed
feat(project): added @Inject and @patch decorators for greatly simplified DI
1 parent 9392073 commit b8305bf

File tree

5 files changed

+56
-8
lines changed

5 files changed

+56
-8
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
export enum ApplicationEvents {
2-
Ready = 'Ready',
2+
Ready = 'Application.Ready',
33
}

src/Library/Controller/ControllerFactoryFactory.ts

Lines changed: 0 additions & 7 deletions
This file was deleted.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export * from './inject';
2+
export * from './patch';
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import 'reflect-metadata';
2+
import { InjectedFactoryPluginType } from '../InjectedServiceFactory';
3+
4+
const metaKey = Symbol('stix:di:inject');
5+
6+
export const inject = (dependency?: any, plugin?: InjectedFactoryPluginType) => {
7+
return (target: Object, property: string) => {
8+
const meta = Reflect.getMetadata(metaKey, target) || [];
9+
10+
meta.push({ property, dependency, plugin });
11+
12+
Reflect.defineMetadata(metaKey, meta, target);
13+
};
14+
};
15+
16+
export const getDependencies = (target: Object) => Reflect.getMetadata(metaKey, target);
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { ServiceManager } from '../ServiceManager';
2+
3+
const metaKey = Symbol('stix:di:patch');
4+
5+
type PatchArgumentsType = {
6+
name: string;
7+
method: Function;
8+
factory: boolean;
9+
};
10+
11+
export const patch = (name: string, method: Function, factory: boolean = false) => {
12+
return (target: ServiceType) => {
13+
const meta = Reflect.getMetadata(metaKey, target) || [];
14+
15+
meta.push({ name, method, factory });
16+
17+
Reflect.defineMetadata(metaKey, meta, target);
18+
};
19+
};
20+
21+
export const applyPatches = (sm: ServiceManager, target: ServiceType) => {
22+
const patches = Reflect.getMetadata(metaKey, target.constructor);
23+
24+
if (!patches) {
25+
return target;
26+
}
27+
28+
return patches.reduce((target: ServiceType, { name, method, factory }: PatchArgumentsType) => {
29+
if (typeof target[name] !== 'function') {
30+
target[name] = (factory ? method(sm, target) : method).bind(target);
31+
}
32+
33+
return target;
34+
}, target);
35+
};
36+
37+
type ServiceType = { [property: string]: any };

0 commit comments

Comments
 (0)