¿Qué tipo debo devolver en las respuestas de AWS Lambda en TypeScript para adaptarme a la Respuesta de Método de AWS API Gateway?
Quiero construir un proyecto adecuado de TypeScript en AWS Lambda.
En este momento, tengo las siguientes definiciones:
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;
};
Pero
En lugar de mi tipo personalizado HttpResponse, quiero usar una definición oficial.
¿Pero qué tipo oficial debo importar y devolver?
Respuesta #1
El paquete @types/aws-lambda proporciona tipos para usar TypeScript dentro de una función AWS Lambda. Para las funciones AWS Lambda invocadas usando el tipo de integración Lambda Proxy de API Gateway, siga los siguientes pasos:
Instala el paquete
yarn add --dev @types/aws-lambda
O si prefieres npm:
npm i --save-dev @types/aws-lambda
Entonces en tu archivo de manejador:
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,
})
}
}
Respuesta #2
Después de días de investigación encontré la respuesta tan cerca ;)
devuelves 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;
};
