Nodejs Spring MVC --支持直接debug ts code
发布于 5 年前 作者 chenkang084 4615 次浏览 来自 分享

最近闲来无事,突发奇想,也顺便练练手,于是就萌生了,能否用typescript的decorator写一个Nodejs SpringMVC,然后就有了这个项目。 该项目支持:

  1. 依赖注入Controller ,Service
  2. 注入GET/POST/PUT/DELETE/PATCH等rest方法
  3. 解析rest api的参数,例如RequestParam
  4. 上传文件支持Multer
  5. 支持在vscode里面直接debug typescript 的代码

想学习如何debug typescript代码的同学可以留意一下,真的很好用。

直接上readMe的部分内容:

Installation

npm i easy-node-ioc --save

Quick Start

Check out the quick start example in test.

Usage

1.Create a Controller

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

2.Create a Service

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

3.Inject Service

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

4.Define 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());
    }
    ...
}

4.Define Start 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");
    });
  }
}

How to debug

if you use vscode , just follow .vscode/launch.json , select Launch Program .
if you see Example app has started. in the console , then means test case start successfully .
Try to call http://localhost:9001/api/test/index .

gitHub地址:https://github.com/chenkang084/easy-node-ioc

说明:由于这个项目也是突发奇想,可能会存在问题。不过,目前我已经用这个包,重写了我公司内部的一个node后台项目,目前一切运行良好。 同时,欢迎issues,如果你觉得还可以,也可以给我一个star。

4 回复

不错是 不错。 但是 AOP 这套思想 被 nest.js 和 midway 早实践过了。 倒是可以基于 nest.js 来搞搞 https://docs.nestjs.cn/

@zuohuadong 嗯。nestjs太重了,有时间我会再继续读读他们的源码。写这个就是让自己了解了一下ts的decorator,加深理解的同时,尝试能否再走的远一点。哈哈,目前,已经在我们内部项目的生产会环境里面运行了一段时间了,看看有没有内存的问题。

@chenkang084 相对 spring 来说,算轻的。

https://github.com/notadd/magnus

我们还有个自动生成工具~

这么好玩的东西,竟然很少有人光顾,真的很好用啊,不忍心被埋没

回到顶部