You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何让方法装饰器触发类实例化(lambda-api场景)

解决lambda-api中类构造函数未执行的问题

问题根源

你用装饰器直接把类的原型方法绑定到lambda-api时,lambda-api调用的是类的静态/原型方法,而非类实例的方法,因此类的构造函数不会被触发,this也无法指向实例,导致依赖初始化失败。

简单解决方案:通过元数据收集路由,实例化时注册

不需要引入额外框架,只需调整装饰器逻辑,先收集路由信息,再在类实例化时绑定实例方法到lambda-api:

  1. 修改装饰器,仅收集路由元数据
// 全局存储路由配置的数组
const routeMetadata = [];

function Get(path) {
  return (target, methodName) => {
    routeMetadata.push({
      method: 'get',
      path,
      methodName
    });
  };
}

function Post(path) {
  return (target, methodName) => {
    routeMetadata.push({
      method: 'post',
      path,
      methodName
    });
  };
}
  1. 调整ProductApi类,构造函数初始化依赖并注册路由
class ProductApi {
  constructor() {
    // 在这里初始化你的Service/Repository依赖
    this.productService = new ProductService();
    this.registerRoutes();
  }

  registerRoutes() {
    // 遍历路由元数据,绑定实例方法到lambda-api
    routeMetadata.forEach(route => {
      // 绑定this到当前实例,确保handler中this指向正确
      const handler = this[route.methodName].bind(this);
      api[route.method](route.path, handler);
    });
  }

  @Get('/health')
  health(req, res) {
    res.status(200).json({ status: 'ok' });
  }

  @Get('/products')
  async getProducts(req, res) {
    const products = await this.productService.getAll();
    res.json(products);
  }

  @Post('/products')
  async createProduct(req, res) {
    const product = await this.productService.create(req.body);
    res.status(201).json(product);
  }
}

// 在lambda handler外部实例化类,确保冷启动时仅初始化一次
new ProductApi();

// 导出lambda handler
exports.handler = api.run.bind(api);

关键说明

  • 实例化操作放在handler外部,利用Lambda冷启动特性,依赖只会初始化一次,提升性能。
  • 通过bind(this)确保路由handler中的this指向ProductApi实例,能正常访问实例化的依赖。
  • 装饰器仅负责收集路由信息,不直接注册到api,把注册逻辑交给实例处理,保证构造函数执行。

内容的提问来源于stack exchange,提问作者Felipe Oriani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 13:30:07