基于koa,在运行时,提供Controller、Route、Parameter、Service等注解的中间件框架,同时给出了不同的NodeJS框架接入chumi的示例
下面是大体架构图
源码地址:github.com/chumijs
⚡️ 快速体验
nodejs >= 16
打开终端,进入空文件夹下,复制如下命令执行即可
echo 'import chumi from "chumi";\nimport Koa from "koa";\nimport HomeController from "./home";\nconst app = new Koa();\napp.use(\n chumi([HomeController], {\n koaBody: {},\n swagger: {},\n })\n);\napp.listen(3000, () => {\n console.log("> http://localhost:3000/api/test?name=123");\n});' > server.ts && echo 'import { Controller, Get, Query } from "chumi";\n@Controller()\nexport default class {\n @Get("/api/test")\n async getTest(@Query("name") name: string) {\n return name;\n }\n}' > home.ts && yarn add chumi tsx && yarn tsx server.ts
✍️ 找个空文件夹,来完整体验下吧 ~
1. 创建文件 server.ts
import chumi from 'chumi'
import Koa from 'koa'
import HomeController from './home'
const app = new Koa();
app.use(chumi([HomeController],{
koaBody:{}, // 支持post请求体解析,这里内置了koa-body
swagger:{} // 支持生成swagger接口文档站点
}));
app.listen(3000,() => {
console.log("> http://localhost:3000/api/test?name=123")
});
2. 创建文件 home.ts
import { Controller, Get, loadService, Query } from "chumi";
import { Context } from "koa";
import service from "./service";
@Controller()
export default class {
ctx: Context;
service = loadService(service);
@Get("/api/test")
async getTest(@Query("name") name: string) {
return (
`name: ${name} ` +
`method: ${this.ctx.method} ` +
`path: ${await this.service.getPath()}`
);
}
}
3. 创建文件 service.ts
import { Service } from "chumi";
import { Context } from "koa";
@Service
export default class {
ctx: Context;
async getPath() {
return this.ctx.path;
}
}
4. 安装依赖
yarn add chumi tsx @types/koa
5. 启动服务
yarn tsx server.ts
🤟 说明
启动服务后,访问地址 http://localhost:3000/api/test?name=123 , 页面上将展示123
至此,一个在
运行时的,使用注解来处理请求的小demo就完成了同时访问该网站(github.com/chumijs),你可以看到vite、egg、midway、nest、next框架接入chumi的示例
🌪 解决装饰器飘红问题
创建文件 tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"esModuleInterop": true,
"moduleResolution": "node",
"target": "ESNext"
}
}
OR
修改vscode配置
打开设置,搜索 experimentalDecorators ,勾上即可