I want to build a proper typescript project on AWS lambda.
Right now, I am having the following definitions:
export type HttpResponse = {
statusCode: number;
headers: {};
body: string;
}
export async function readCollection (event, context, callback): Promise<HttpResponse>{
console.log(event); // Contains incoming request data (e.g., query params, headers and more)
const data = [
{
id: "a7b5bf50-0b5b-11e9-bc65-6bfc39f23288",
name: "some thing",
uri: `/notifications/a7b5bf50-0b5b-11e9-bc65-6bfc39f23288`
}
]
const response = {
statusCode: 200,
headers: {
},
body: JSON.stringify({
status: "ok",
data: data
})
};
return response;
};
But
Instead of my custom HttpResponse
type, I want to use an official definition.
But which official type do I import and return?
You can use the Node. js runtime to run TypeScript code in AWS Lambda.
Update Lambda function code, deploy and publish a new version. Go to API Gateway > stages > stage variables and update the “lambda_function_version” value with the new version number. Run the Lambda add-permissions command for this new version. Deploy the API on the required stage.
The @types/aws-lambda package provides types for using TypeScript inside of an AWS Lambda function. For AWS Lambda functions invoked using API Gateway's Lambda Proxy integration type take the following steps:
Install the package
$ yarn add --dev @types/aws-lambda
Or if you prefer npm:
$ npm i --save-dev @types/aws-lambda
Then in your handler file:
import { APIGatewayProxyEvent, Context, APIGatewayProxyResult } from "aws-lambda"
export async function hello (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> {
return {
statusCode: 200,
body: JSON.stringify({
message: 'Hello world',
input: event,
})
}
}
After days of research I found the answer so close ;)
you return Promise<APIGateway.MethodResponse>
import { APIGateway } from "aws-sdk";
export async function readCollection (event, context, callback): Promise<APIGateway.MethodResponse> {
console.log(event); // Contains incoming request data (e.g., query params, headers and more)
const data = [
{
id: "a7b5bf50-0b5b-11e9-bc65-6bfc39f23288",
name: "some thing",
uri: `/notifications/a7b5bf50-0b5b-11e9-bc65-6bfc39f23288`
}
]
const response = {
statusCode: "200",
headers: {
},
body: JSON.stringify({
status: "ok",
data: data
})
};
return response;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With