用Decorator实现依赖注入,像Java一样写后台

最近闲来无事,突发奇想,也顺便练练手,于是就萌生了,能否用typescript的decorator写一个Nodejs SpringMVC,通过依赖注入,自动实现文件加载,实例化等。然后就有了这个项目。 该项目支持:

依赖注入Controller ,Service 注入GET/POST/PUT/DELETE/PATCH等rest方法 解析rest api的参数,例如RequestParam 上传文件支持Multer 支持在vscode里面直接debug typescript 的代码 想学习如何debug typescript代码的同学可以留意一下,真的很好用。

easy-node-ioc

用 Typescript 的装饰器实现依赖注入,就像我们使用 Spring MVC 框架一样,web 框架使用的是 Express

安装

npm i easy-node-ioc --save-dev

快速开始使用

git clone https://github.com/chenkang084/easy-node-ioc.git
npm i
NODE_ENV=development npx ts-node demo/App.ts

执行完以上命令,将在命令行输出 Example app has started,代码项目已正常经启动起来了,尝试访问 http://localhost:9001/api/test/index ,页面将返回 OK。

使用

1.创建 Controller

import { Controller} from 'easy-node-ioc';
@Controller('/test')
class TestControl {
    ...
}

2.创建 Service

import { Service } from 'easy-node-ioc';
@Service('')
class TestService {
    ...
}

3.将 Service 注入到 Controller 中

import { Autowired,Controller } from 'easy-node-ioc';
@Controller('/test')
class TestControl {
    @Autowired
    testService: TestService;
    ...
}
 

4.在 Controller 中定义 Rest API,例如 GET,POST,PUT,DELETE,PATCH

import { Autowired,Controller,GET,RequestParam } from 'easy-node-ioc';
@Controller('/test')
class TestControl {
    @Autowired
    testService: TestService;
    @Get('/index')
    index(@RequestParam('age') age: number, req: Request, res: Response) {
        console.log('index method');
        this.dbService.queryDb();

        res.status(200).send(this.testService.queryDb());
    }
    ...
}
 

5.定义 App,添加 ComponentScan,添加 Bootstrap 注解到 App 类

import { Bootstrap, ComponentScan } from '../';
@ComponentScan(join(__dirname, './Controller.ts'))
@Bootstrap
class App {
  constructor() {}

  app = express();

  main() {
    const server = http.createServer(this.app);

    server.listen(9001, function() {
      console.log('Example app listening at http://%s:%s');
    });
  }
}
 

第 5 步是非常关键的,ComponentScan 注解负责告诉easy-node-ioc去指定目录读取 js/ts 文件,在读取文件的过程中,根据 Decorator 定义,向容器中添加对应实例,在 Boostrap 方法里面根据文件依赖,去容器中获取已经实例化的对象(如果对象没有实例化,就立即实例化),等所有的依赖都注入完成,执行main方法。

测试

npm test 本项目已经写了一些基础的 test case,可以在项目路径下的 tests 目录查看。

Debug

.vscode目录的 launch.json 文件中,已经配置好了 debug 相关的代码,你可以直接在vscode中使用 F5 进行 debug,这样更方便你了解项目是如何实现的。

其他

如果你对decorator比较感兴趣,可以查看相关资料,了解 decorator 如何使用。

我建立了一个微信群,如果你对这个小工具感兴趣,可以加群,或者如果你有什么问题,也可以进群交流。

猜你喜欢

转载自www.cnblogs.com/rengised/p/12175253.html