@decorators/express

中文文档
3.0.0发布于 2023/07/28MITTypeScriptCommonJS零依赖近 30 天下载 6657

node decorators - decorators for express library

原始使用文档
文档目录3 节
  1. Installation
  2. API
  3. Example Express Application and Controller:

Node Decorators

Project implements decorators for modern tools for NodeJS like:

Installation

npm install @decorators/express --save

API

Functions

  • attachControllers(app: Express.Application | Express.Router, controllers: Controller[]) - attach controllers to express application
  • attachControllerInstances(app: Express.Application | Express.Router, controllers: Controller[]) - attach already existing instances of controllers

Decorators

Class
  • @Controller(baseUrl: string, middleware?: Middleware[]), @Controller(baseUrl: string, routerOptions: RouterOptions, middleware?: Middleware[]) - Registers controller for base url
Method
  • @All(url: string, middleware?: Middleware[]) - Registers all routes
  • @Get(url: string, middleware?: Middleware[]) - Registers get route
  • @Post(url: string, middleware?: Middleware[]) - Registers post route
  • @Put(url: string, middleware?: Middleware[]) - Registers put route
  • @Delete(url: string, middleware?: Middleware[]) - Registers delete route
  • @Patch(url: string, middleware?: Middleware[]) - Registers patch route
  • @Options(url: string, middleware?: Middleware[]) - Registers options route
  • @Head(url: string, middleware?: Middleware[]) - Registers head route
  • @Status(code: number) - Specifies status code for the route

where middleware is the class that implements Middleware interface.

To use class, import Middleware interface and implement it, like so:

import { Middleware } from '@decorators/express';

class UserMiddleware implements Middleware {
  public use(request: Request, response: Response, next: NextFunction): void {
    next();
  }
}

or a simple function

function userMiddleware(request: Request, response: Response, next: NextFunction): void {
  next();
}
Parameter
  • @Request(property?: string) (alias @Req(property?: string)) - Returns express req object or any other object, if name was specified
  • @Response() (alias @Res) - Returns express res object
  • @Next() - Returns express next function
  • @Params(param?: string) - Express req.params object or single param, if param name was specified
  • @Query(param?: string) - Express req.query object or single query param, if query param name was specified
  • @Body(param?: string) - Express req.body object or single body param, if body param name was specified
  • @Headers(property?: string) - Express req.headers object or single headers param, if headers param name was specified
  • @Cookies(param?: string) - Express req.body object or single cookies param, if cookies param name was specified

Error middleware

To add error middleware, that handles unhandled errors simply implement ErrorMiddleware interface and provide it using ERROR_MIDDLEWARE token, like so:

import { Container, ErrorMiddleware, ERROR_MIDDLEWARE } from '@decorators/express';

@Injectable()
class ServerErrorMiddleware implements ErrorMiddleware {
  public use(error: Error, request: Request, response: Response, next: NextFunction) {
    next();
  }
}

Container.provide([
  { provide: ERROR_MIDDLEWARE, useClass: ServerErrorMiddleware }
]);

or as a function

import { Container, ERROR_MIDDLEWARE } from '@decorators/express';

function serverErrorMiddleware(error: Error, request: Request, response: Response, next: NextFunction) {
  next();
}

Container.provide([
  { provide: ERROR_MIDDLEWARE, useValue: serverErrorMiddleware }
]);

Dependency injection

This module supports dependency injection provided by @decorators/di module. For example, see the full example below.

Example Express Application and Controller:

import {
  Response, Params, Controller, Get,
  attachControllers, Middleware
} from '@decorators/express';

@Controller('/')
class UsersController {

  constructor(private userService: UserService) {}

  @Get('/users/:id')
  getData(@Response() res, @Params('id') id: string) {
    res.send(this.userService.findById(id));
  }
}

let app = express();
attachControllers(app, [UsersController]);

app.listen(3000);

You can also attach controllers to express.Router instance. This is useful when you want to namespace all of the routes with a prefix:

import { attachControllers } from '@decorators/express';

const apiRouter = express.Router();
attachControllers(apiRouter, [UsersController]);

app.use('/v1/api', apiRouter);

You can also use custom decorators as middleware :

Custom Decorator

import { attachMiddleware } from "@decorators/express";
import {Request,Response,NextFunction} from '@decorators/express/node_modules/express';

export function Access(key: string) {
    return function (target: any,propertyKey: string,descriptor: PropertyDescriptor) {
      attachMiddleware(target,propertyKey,(req : Request,res : Response,next : NextFunction)=>{
            if(["CAN_ACCESS_TEST","CAN_ACCESS_HOME"].includes(key)){
              next();
            }else{
              res.send("ACCESS DENIED");
            }
        })
    };
  }

Controller Code

@Controller("/")
export class MainController {

    @Access("CAN_ACCESS_TEST")
    @Get("/test")
    getB() {
        return "You can access the test";
    }

    @Access("CAN_ACCESS_HOME")
    @Get("/home")
    getB() {
        return "You can access the home";
    }
}

Note:- Please use custom decorators before express decorators otherwise system will not detect any controller metadata and your decorator will not invoked.

Will work:

    @Access("CAN_ACCESS_TEST")
    @Get("/test")
    getB() {
        return "You can access the test";
    }

Will not work:

    @Get("/test")
    @Access("CAN_ACCESS_TEST")
    getB() {
        return "You can access the test";
    }

版本与发布记录

@decorators/express 共发布 24 个版本,首次发布于 2016/09/27;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.0.0latest2023/07/283 年前
2.9.42023/06/283 年前
2.9.32023/04/043 年前
2.9.12023/02/043 年前
2.9.02023/01/303 年前
2.8.12023/01/303 年前

关于 @decorators/express 的常见问题

@decorators/express 是什么?

node decorators - decorators for express library

如何安装 @decorators/express?

在项目目录运行 npm install @decorators/express,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@decorators/di(^3.0.0)、express(^4.16.3)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@decorators/express 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@decorators/express 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@decorators/express 可以商用吗?

@decorators/express 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@decorators/express 的下载量有多少?

根据 npm 官方下载统计,@decorators/express 在 2026/10/12 – 2026/11/10 这 30 天内被下载 6,657 次,日均约 222 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@decorators/express 还在维护吗?

最新版本 3.0.0 发布于 2023/07/28(3 年前);至今共发布 24 个版本,其中过去 12 个月发布了 0 个;首次发布于 2016/09/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。