@micro.ts/core
Version:
Microservice framework with Typescript
88 lines (87 loc) • 3.11 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Inject = exports.getInjectParamTypes = exports.getConstructorParams = exports.Service = void 0;
const DiRegistry_1 = require("./DiRegistry");
const DiOptionsTypes_1 = require("./types/DiOptionsTypes");
/**
* Provide custom configuration (transient, or scoped) for a service to register it in the DI container
* @param options
* @param registry
*/
function Service(options, registry = DiRegistry_1.ContainerRegistry) {
return (target) => {
let constructorArgs = getInjectParamTypes(target);
if (!constructorArgs) {
const paramTypes = getConstructorParams(target);
constructorArgs = paramTypes.map((x) => {
return { type: x };
});
Reflect.defineMetadata('design:injectparamtypes', constructorArgs, target);
}
options = options || {};
options.ctorParams = constructorArgs;
if (!options.scope) {
options.scope = DiOptionsTypes_1.ServiceScope.Singleton;
}
registry.bind(target, options);
};
}
exports.Service = Service;
/**
* Get constructor parameters even in constructor less services
* @param target
*/
function getConstructorParams(target) {
const paramTypes = Reflect.getOwnMetadata('design:paramtypes', target) || [];
if (paramTypes.length === 0) {
const superClass = Object.getPrototypeOf(target);
if (!!superClass && superClass !== Object) {
return getConstructorParams(superClass);
}
return [];
}
return paramTypes;
}
exports.getConstructorParams = getConstructorParams;
/**
* Get Inject param types even in constructor less services
* @param target
*/
function getInjectParamTypes(target) {
const paramTypes = Reflect.getOwnMetadata('design:injectparamtypes', target);
if (!paramTypes) {
const superClass = Object.getPrototypeOf(target);
if (!!superClass && superClass !== Object) {
return getInjectParamTypes(superClass);
}
}
return paramTypes;
}
exports.getInjectParamTypes = getInjectParamTypes;
/**
* Decorator is used in constructor arguments, for services of app controllers
* @param key
*/
function Inject(key) {
return (target, _propertyKey, parameterIndex) => {
if ((!!parameterIndex || parameterIndex === 0) &&
typeof parameterIndex === 'number') {
let ctorMetadata = getInjectParamTypes(target);
if (!ctorMetadata) {
const constructorArgs = Reflect.getOwnMetadata('design:paramtypes', target) || [];
ctorMetadata = constructorArgs.map((x) => {
return { type: x };
});
}
ctorMetadata[parameterIndex].injectOptions = {
key: key || ctorMetadata[parameterIndex].type,
};
Reflect.defineMetadata('design:injectparamtypes', ctorMetadata, target);
}
else {
if (!parameterIndex) {
}
}
};
}
exports.Inject = Inject;