vue-di-container
Version:
Dependency injection container for Vue
128 lines (127 loc) • 3.52 kB
JavaScript
export class ChainProviderResolver {
constructor(resolvers) {
this.resolvers = resolvers;
}
resolve(provider) {
for (const resolver of this.resolvers) {
const def = resolver.resolve(provider);
if (def) {
return def;
}
}
}
}
class ValueDefinition {
constructor(key, value) {
this.key = key;
this.value = value;
}
get(container) {
return this.value;
}
}
export class ValueProviderResolver {
isValueProvider(provider) {
return provider.value !== undefined;
}
resolve(provider) {
if (this.isValueProvider(provider)) {
return new ValueDefinition(provider.key, provider.value);
}
}
}
class ClassDefinition {
constructor(key, cls, args, props) {
this.key = key;
this.cls = cls;
this.args = args;
this.props = props;
}
get(container) {
const argsValues = this.args.map(key => key ? container.get(key) : undefined);
const instance = new this.cls(...argsValues);
for (const prop of Object.keys(this.props)) {
instance[prop] = container.get(this.props[prop]);
}
return instance;
}
}
export class ClassProviderResolver {
constructor(metadata) {
this.metadata = metadata;
}
isCtor(providerOrKey) {
return typeof providerOrKey === 'function';
}
isFullClassProvider(provider) {
return !!provider.class;
}
resolve(provider) {
let key;
let cls;
let args = [];
let props = {};
if (this.isCtor(provider)) {
key = cls = provider;
}
else if (this.isFullClassProvider(provider)) {
key = provider.key;
cls = provider.class;
args = provider.args || [];
props = provider.props || {};
}
else if (this.isCtor(provider.key)) {
key = cls = provider.key;
args = provider.args || [];
props = provider.props || {};
}
if (key && cls) {
const argKeys = this.metadata.getParameterKeys(cls, args);
const propKeys = this.metadata.getPropertyKeys(cls, props);
return new ClassDefinition(key, cls, argKeys, propKeys);
}
}
}
class FactoryDefinition {
constructor(key, factory, args) {
this.key = key;
this.factory = factory;
this.args = args;
}
get(container) {
const argsValues = this.args.map(key => key ? container.get(key) : undefined);
const factory = this.factory;
const instance = factory(...argsValues);
return instance;
}
}
export class FactoryProviderResolver {
isFactoryProvider(provider) {
return !!provider.factory;
}
resolve(provider) {
if (this.isFactoryProvider(provider)) {
return new FactoryDefinition(provider.key, provider.factory, provider.args || []);
}
}
}
class AliasDefinition {
constructor(key, aliasOf) {
this.key = key;
this.aliasOf = aliasOf;
}
get(container) {
return container.get(this.aliasOf);
}
}
export class AliasProviderResolver {
isAliasProvider(provider) {
return !!provider.aliasOf;
}
resolve(provider) {
if (this.isAliasProvider(provider)) {
return new AliasDefinition(provider.key, provider.aliasOf);
}
return undefined;
}
}