还能这样写控制器?让你的nodejs开发更简单。

982 阅读1分钟

开发这个包的目的

使用Express开发的时候,随着项目的日益壮大,越来越多的路由处理函数、中间件,给你的代码造成无法维护的局面。

    app.post('/api/post', handle1)
    app.get('/api/post2', handle2)
    app.post('/api/post3', handle3)
    app.get('/api/post4', handle4)
    ...

如果你还在使用Nest,接受不了Nest的庞大概念,只是喜欢Nest的装饰器路由规则。 既要Express的灵活,又要Nest的项目可维护性,所以有了这个包。

怎么使用

安装

npm i enpd

配置你的 tsconfig.json 文件:

{ "experimentalDecorators": true }

首先,创建你的控制器。

import { Get, Post } from "enpd";

class Test {
  // GET: /test
  @Get()
  findAll(req: express.Request, res: express.Response) {
    res.json(req.query);
  }

  // POST: /test/create/:id
  @Post("create/:id")
  create(req, res) {
    res.json(req.params);
  }
}

然后使用它在你的 Express 应用中。

import { use } from "enpd";

const app = express();
use.setup(app);

use("test", Test);
use("user", User);
app.listen(8080);

提供的装饰器

  • @Get | @Post | @Put | @Delete | @Patch
  • @Body | @Query | @Param
  • @Use

@Body | @Query | @Param

快速校验的你的参数,包含 body|query|param 中的参数。

import { e } from "enpd";

@Post("create/:id")
@Body({
  name: e.sting(),
  phone: e.string().pattern(/^\d{11}$/).errMsg("手机号有误")
  tags: e.func((val) => Array.isArray(val) && val.length === 2),
})
@Param({ id: z.snumber() })
create(req, res) { }

支持的验证类型和传参方式。

// e.
// string
// number
// snumber
// array
// boolean
// sboolean
// object
// enums
// func

@Use

中间件装饰器:方法级别的中间件,执行的顺序在该方法之前,可用于权限校验、拦截等。

另一种说法是类似于Spring: AOP的功能,让请求处理函数拥有面向切面编程的能力。

@Use(async (req, res, next) => {
  console.log("before");
  await next();
  console.log("after");
})
@Get()
findAll(req, res) {}