rocker
轻量级的IOC框架,
Usage
安装 npm install @vdian/rocker
代码示例
import {Container} from '@vdian/rocker';
class User{
id:string = 'testId';
name:string = 'testName';
}
abstract class UserService{
abstract getUser(id:string):User;
}
Container.provides(class extends UserService {
async getUser(_id: string): User {
return new User();
}
});
Container.provides([UserService,() => {
return new class extends UserService {
async getUser(_id: string): User {
return new User();
}
}();
}]);
class Control{
@Inject
userService:UserService;
test(){
let user:User = this.userService.getUser();
console.log(user);
}
}
(new Control()).test();
场景:RPC调用
import {Container, Inject} from '@vdian/rocker'
let RPC = {
config: function (_cfg: { serviceUrl: string, interfaces: Function[] }) {
if (_cfg.interfaces) {
_cfg.interfaces.forEach((_type: FunctionConstructor) => {
if (_type.prototype) {
let newObj = {}, proto = _type.prototype;
let nms = Object.getOwnPropertyNames(proto);
if (nms) {
nms.forEach((nm) => {
if (nm != 'constructor' && typeof(proto[nm]) === 'function') {
newObj[nm] = function () {
return arguments[0];
}
}
})
}
Container.provides([_type, () => {
return newObj;
}])
}
})
}
}
}
class Product {
getById(id: string): string {
return null;
}
}
RPC.config({
serviceUrl: null,
interfaces: [Product]
})
class Service {
@Inject
product: Product;
test() {
let id: string = 'tid';
let rst = this.product.getById(id);
console.log(rst);
}
}
new Service().test();