I have an api gateway that I need to integrate with a lambda to mutate some request data and then pass it over to another service.
I have my lambda set up synchronously (event, context, callback), and works fine for synchronous requests. However, when I add a "Proxy" functionality to the lambda (make a request to another endpoint, get the response and return said response to the api gateway, I can't seem to be able to handle the promise correctly.
Here's some pseudocode of what I have:
const { fetch } = require('node-fetch');
const proxyMethod = (event, callback) => {
const request = // valid fetch request
fetch(request)
.then(result => callback(null, result))
.catch(error => callback(Error(error));
}
exports.handler = (event, context, callback) => {
proxyMethod(event, callback);
}
The issue is that I don't think I'm handling the promise synchronously, and using async / await in "proxyMethod" basically has no effect or the callback is not waiting for the promise to be resolved.
This is what I'm getting in the API gateway logs:
Sending request to https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-1:########:function:#########/invocations
Received response. Status: 200, Integration latency: 749 ms
Endpoint response headers: {Date=Tue, 21 Jul 2020 02:11:31 GMT, Content-Type=application/json, Content-Length=4, Connection=keep-alive, x-amzn-RequestId=######, x-amzn-Remapped-Content-Length=0, X-Amz-Executed-Version=$LATEST, X-Amzn-Trace-Id=root=########;sampled=0}
Endpoint response body before transformations: null
Execution failed due to configuration error: Malformed Lambda proxy response
Gateway response type: DEFAULT_5XX with status code: 502
Found helpful information here. In a bunch of different places, turns out node runtime supports using the async flow, so I needed to use await to wait for the fetch request, and then await again in the "response.json()" to get the response from the service downstream.