Skip to content

Commit

Permalink
feat(di): provider fn can be an object
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzofox3 committed Feb 25, 2024
1 parent 8b8dc26 commit 38d338c
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions packages/di/src/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
const rootRegistry = {};
const registrySymbol = Symbol('registry');

export const provide = (providerFn) => (comp) =>
function* ({ $host, ...rest }) {
const factorify = (factoryLike) =>
typeof factoryLike === 'function' ? factoryLike : () => factoryLike;

export const provide = (providerFn) => (comp) => {
const _providerFn = factorify(providerFn);
return function* ({ $host, ...rest }) {
yield; // The element must be mounted, so we can look up the DOM tree
$host[registrySymbol] = Object.assign(
Object.create(
$host.closest('[provider]')?.[registrySymbol] ?? rootRegistry,
),
providerFn({ $host, ...rest }),
_providerFn({ $host, ...rest }),
);
$host.toggleAttribute('provider');

Expand All @@ -21,6 +25,7 @@ export const provide = (providerFn) => (comp) =>

yield* instance;
};
};

export const inject = (comp) =>
function* ({ $host, ...rest }) {
Expand All @@ -32,9 +37,7 @@ export const inject = (comp) =>
if (!Reflect.has(services, prop)) {
throw new Error(`could not resolve injectable "${prop}"`);
}
const factoryLike = services[prop];
const factory =
typeof factoryLike === 'function' ? factoryLike : () => factoryLike;
const factory = factorify(services[prop]);
return factory(proxy);
},
});
Expand Down

0 comments on commit 38d338c

Please sign in to comment.