Issue
This Content is from Stack Overflow. Question asked by adamwright000
I’ve recently switched to writing my AWS Lambda functions in TypeScript from vanillaJS as I use Angular so thought it’d be better for better muscle memory, but am running into the following error when trying to execute a method inside the lambda function.
{
"errorType": "TypeError",
"errorMessage": "this.test is not a function",
"stack": [
"TypeError: this.test is not a function",
" at Runtime.lambda [as handler] (/var/task/index.js:17:249)",
" at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1028:29)"
]
}
How do I fix this? Have tried a few different ways but to no avail so far. P.S, I don’t use Serverless framework or anything similar. This is just me writing and uploading as ZIP with AWS CLI. Function executes without this problem.
import { Context, APIGatewayProxyResult, APIGatewayEvent } from 'aws-lambda';
class Index {
constructor() { }
test() {
return "test"
}
public async lambda(event: APIGatewayProxyResult, context: Context): Promise<any> {
return {
statusCode: 200,
body: this.test()
}
}
}
export const index = new Index()
export const handler = index.lambda
Solution
Fixed thanks to GitHub Co-Pilot suggestion (and btw, anyone that doesn’t have this, $10 per month is a no-brainer. It’s fantastic)
Needed to bind this to lambda function in my constructor.
constructor() {
this.lambda = this.lambda.bind(this)
}
This Question was asked in StackOverflow by adamwright000 and Answered by adamwright000 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.