Skip to content

Commit 03f5fac

Browse files
committed
chore(*): Rename __factory identifier to __ident and apply it to mocked methods as well
1 parent 0a2d622 commit 03f5fac

File tree

2 files changed

+37
-30
lines changed

2 files changed

+37
-30
lines changed

src/repository/repository.ts

Lines changed: 3 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { applyIdentityProperty } from '../utils/applyIdentityProperty';
2+
13
// eslint-disable-next-line
24
type Factory = (...args: any[]) => any;
35

@@ -16,36 +18,7 @@ export class Repository {
1618
}
1719

1820
public registerFactory(key: string, factory: Factory): void {
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;
21+
this._repository[key] = applyIdentityProperty(factory, key);
4922
}
5023

5124
public getFactory(key: string): Factory {

src/utils/applyIdentityProperty.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// eslint-disable-next-line
2+
type Function<K> = (...args: any[]) => K;
3+
type IdentityFlavored<K> = K & { __ident?: string };
4+
5+
export function applyIdentityProperty<K extends object, T extends Function<K>>(target: T, identity: string): T {
6+
return new Proxy(
7+
target,
8+
{
9+
apply(func: T, _this: unknown, args: Parameters<T>): IdentityFlavored<K> | undefined {
10+
const t: IdentityFlavored<K> = func(...args);
11+
12+
if (typeof t === 'undefined') {
13+
return;
14+
}
15+
16+
if (!(t instanceof Object)) {
17+
return t;
18+
}
19+
20+
if (typeof t.__ident !== 'undefined') {
21+
return t;
22+
}
23+
24+
Object.defineProperty(t, '__ident', {
25+
enumerable: false,
26+
writable: false,
27+
value: identity,
28+
});
29+
30+
return t;
31+
},
32+
},
33+
);
34+
}

0 commit comments

Comments
 (0)