Skip to content

Commit

Permalink
Add redirect function
Browse files Browse the repository at this point in the history
  • Loading branch information
betula committed Jun 9, 2019
1 parent 114f037 commit 6803976
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
17 changes: 16 additions & 1 deletion index.ts
@@ -1,6 +1,9 @@
import "reflect-metadata";

type Type<T = any> = new (...args: any) => T;

const instances = new Map();
const redirects = new Map();

export function provide(target: object, propertyKey: string): any {
const Class = Reflect.getMetadata("design:type", target, propertyKey);
Expand All @@ -20,14 +23,26 @@ export function provide(target: object, propertyKey: string): any {
};
}

export function resolve<T>(Class: new (...args: any) => T): T {
export function resolve<T>(Class: Type<T>): T {
Class = redirects.get(Class) || Class;
let instance = instances.get(Class);
if (!instance) {
instances.set(Class, (instance = new Class()));
}
return instance;
}

export function redirect(from: Type, to: Type): void;
export function redirect(...pairs: Type[][]): void;
export function redirect(...args: any[]): void {
if (Array.isArray(args[0])) {
(args as Type[][]).forEach((pair) => redirect(pair[0], pair[1]));
} else {
redirects.set(args[0], args[1]);
}
}

export function reset() {
instances.clear();
redirects.clear();
}
4 changes: 3 additions & 1 deletion tslint.json
Expand Up @@ -9,7 +9,9 @@
true,
"double"
],
"variable-name": false
"variable-name": false,
"no-parameter-reassignment": false,
"ter-arrow-parens": [true, "always"]
},
"rulesDirectory": []
}

0 comments on commit 6803976

Please sign in to comment.