Skip to content

Commit ef93ab5

Browse files
committed
enhancement(repository): Add hidden __factory property to mocks to differentiate them in conditional typing
1 parent 7480aad commit ef93ab5

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

src/repository/repository.ts

+32-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
type Factory = Function;
1+
// eslint-disable-next-line
2+
type Factory = (...args: any[]) => any;
23

34
export class Repository {
45
private readonly _repository: { [key: string]: Factory };
@@ -15,7 +16,36 @@ export class Repository {
1516
}
1617

1718
public registerFactory(key: string, factory: Factory): void {
18-
this._repository[key] = factory;
19+
const proxy: Factory = new Proxy(
20+
factory,
21+
{
22+
apply(target: Factory, _this: unknown, args: Parameters<Factory>): ReturnType<Factory> {
23+
const mock: ReturnType<Factory> = target(...args);
24+
25+
if (typeof mock === 'undefined') {
26+
return;
27+
}
28+
29+
if (!(mock instanceof Object)) {
30+
return mock;
31+
}
32+
33+
if (typeof mock.__factory !== 'undefined') {
34+
return mock;
35+
}
36+
37+
Object.defineProperty(mock, '__factory', {
38+
enumerable: false,
39+
writable: false,
40+
value: key,
41+
});
42+
43+
return mock;
44+
},
45+
},
46+
);
47+
48+
this._repository[key] = proxy;
1949
}
2050

2151
public getFactory(key: string): Factory {

0 commit comments

Comments
 (0)