Skip to content

Commit

Permalink
fix(create-injectable): allow returning proxies from factory function
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuamorony committed Apr 26, 2024
1 parent 7291426 commit cae96e7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
24 changes: 24 additions & 0 deletions libs/ngxtension/create-injectable/src/create-injectable.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,28 @@ describe(createInjectable.name, () => {
expect(service.someProp).toEqual(1);
});
});

it('should be able to return proxy from factory function', () => {
const MyInjectable = createInjectable(() => {
const test = () => {};

Object.defineProperty(test, 'name', {
value: 'josh',
});

return new Proxy(test, {
get(target, property, receiver) {
return Reflect.get(target, property, receiver);
},
apply(target, thisArg, argumentsList) {
return Reflect.apply(target, thisArg, argumentsList);
},
});
});

TestBed.runInInjectionContext(() => {
const service = inject(MyInjectable);
expect(service.name).toEqual('josh');
});
});
});
13 changes: 12 additions & 1 deletion libs/ngxtension/create-injectable/src/create-injectable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,18 @@ export function createInjectable<TFactory extends (...args: any[]) => object>(
@Injectable({ providedIn: providedIn === 'scoped' ? null : providedIn })
class _Injectable {
constructor() {
Object.assign(this, factory());
const result: any = factory();

for (const key of Reflect.ownKeys(result)) {
Object.defineProperty(this, key, {
get: () => result[key],
set: (value: any) => {
result[key] = value;
},
enumerable: true,
configurable: true,
});
}
}
}

Expand Down

0 comments on commit cae96e7

Please sign in to comment.