Skip to content

Commit

Permalink
enhancement(repository): Add hidden __factory property to mocks to di…
Browse files Browse the repository at this point in the history
…fferentiate them in conditional typing
  • Loading branch information
martinjlowm committed May 9, 2020
1 parent 7480aad commit ef93ab5
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions src/repository/repository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
type Factory = Function;
// eslint-disable-next-line
type Factory = (...args: any[]) => any;

export class Repository {
private readonly _repository: { [key: string]: Factory };
Expand All @@ -15,7 +16,36 @@ export class Repository {
}

public registerFactory(key: string, factory: Factory): void {
this._repository[key] = factory;
const proxy: Factory = new Proxy(
factory,
{
apply(target: Factory, _this: unknown, args: Parameters<Factory>): ReturnType<Factory> {
const mock: ReturnType<Factory> = target(...args);

if (typeof mock === 'undefined') {
return;
}

if (!(mock instanceof Object)) {
return mock;
}

if (typeof mock.__factory !== 'undefined') {
return mock;
}

Object.defineProperty(mock, '__factory', {
enumerable: false,
writable: false,
value: key,
});

return mock;
},
},
);

this._repository[key] = proxy;
}

public getFactory(key: string): Factory {
Expand Down

0 comments on commit ef93ab5

Please sign in to comment.