带有typescript的AWS Lambda正在获取异步处理程序内未定义的undefined属性



在此处键入新手脚本。我正在通过将typescript与类一起使用来开发AWS Lambda函数。我在最后导出一个async处理程序。当我从AWS SAM CLI调用我的函数时,我得到的错误为;

在运行时无法读取未定义的属性"test","stack":[类型错误:在运行时不能读取未定义"test"的属性"test"。handler(/var/task/src/lambda/create cost lambda.js:12:56(","在运行时.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();

这里有一个非常基本的类表示一个存储库。

foobar存储库.ts

export class FoobarRepository {
private readonly awesomeValue: string;
constructor() {
this.awesomeValue = 'John Doe';
}
async test(): Promise<string> {
return this.awesomeValue;
}
}

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

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

我将按如下方式解决此问题:

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

你也可以问自己,这需要成为一门课吗?答案是:可能不会。你的样品中没有任何收获。

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,
};
}

更少的行,没有多余的状态。Javascript不是Java=(

相关内容

最新更新