AWS Lambda with typescript getting Cannot read 属性 of undefined inside async handler

AWS Lambda with typescript getting Cannot read property of undefined inside async handler

这里是 Typescript 新手。我正在使用带有 classes 的打字稿来处理 AWS Lambda 函数。我在最后导出一个 async 处理程序。当我从 AWS SAM CLI 调用我的函数时,出现以下错误:

{"errorType":"TypeError","errorMessage":"Cannot read property 'test' of undefined","stack":["TypeError: Cannot read property 'test' of undefined"," at Runtime.handler (/var/task/src/lambda/create-cost-lambda.js:12:56)"," at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"]}

创建成本-lambda.ts

class CreateCostLambda {
    private readonly foobarRepository: FoobarRepository;

    constructor() {
        this.foobarRepository = new FoobarRepository();
    }

    async handler(event: APIGatewayProxyEventV2) : Promise<APIGatewayProxyResultV2> {
        const result = await this.foobarRepository.test();
        console.log(result);

        return {
            body: JSON.stringify(result),
            statusCode: 200,
        };
    }
}

export const { handler } = new CreateCostLambda();

这是一个非常基本的 class 代表一个存储库。

foobar-repository.ts

export class FoobarRepository {
    private readonly awesomeValue: string;

    constructor() {
        this.awesomeValue = 'John Doe';
    }

    async test(): Promise<string> {
        return this.awesomeValue;
    }
}

我几乎可以肯定这是因为我导出处理程序的方式以及 aws-sam 如何在内部运行处理程序。但我可能是错的,它可能是我遗漏的打字稿。如果您需要更多信息,请告诉我,非常感谢您的帮助!

简短的版本是,如果您从 class 传递函数,它会丢失对 this 的引用。

我会按如下方式解决这个问题:

const createCostLambda = new CreateCostLambda();
export const handler = createCostLambda.handler.bind(createCostLambda);

你也可以问问自己,这需要是class吗?答案是:可能不会。在您的样本中没有任何收获。

const foobarRepository = new FoobarRepository();
export async function handler(event: APIGatewayProxyEventV2) : Promise<APIGatewayProxyResultV2> {
   const result = await foobarRepository.test();
   console.log(result);

   return {
     body: JSON.stringify(result),
     statusCode: 200,
   };
}

更少的行,没有不需要的状态。 Java脚本不是 Java =)