最近闲来无事,突发奇想,也顺便练练手,因而就萌生了,可否用typescript的decorator写一个Nodejs SpringMVC,经过依赖注入,自动实现文件加载,实例化等。而后就有了这个项目。 该项目支持:javascript
依赖注入Controller ,Service 注入GET/POST/PUT/DELETE/PATCH等rest方法 解析rest api的参数,例如RequestParam 上传文件支持Multer 支持在vscode里面直接debug typescript 的代码 想学习如何debug typescript代码的同窗能够留意一下,真的很好用。java
用 Typescript 的装饰器实现依赖注入,就像咱们使用 Spring MVC 框架同样,web 框架使用的是 Express。node
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。git
import { Controller} from 'easy-node-ioc';
@Controller('/test')
class TestControl {
...
}
复制代码
import { Service } from 'easy-node-ioc';
@Service('')
class TestService {
...
}
复制代码
import { Autowired,Controller } from 'easy-node-ioc';
@Controller('/test')
class TestControl {
@Autowired
testService: TestService;
...
}
复制代码
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());
}
...
}
复制代码
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
方法。github
npm test
本项目已经写了一些基础的 test case,能够在项目路径下的 tests 目录查看。web
在.vscode
目录的 launch.json 文件中,已经配置好了 debug 相关的代码,你能够直接在vscode
中使用 F5 进行 debug,这样更方便你了解项目是如何实现的。typescript
若是你对decorator
比较感兴趣,能够查看相关资料,了解 decorator 如何使用。express
我创建了一个微信群,若是你对这个小工具感兴趣,能够加群,或者若是你有什么问题,也能够进群交流。npm