Skip to content

Commit 7ef2d64

Browse files
committed
handle defaulting response for v2
1 parent d68035f commit 7ef2d64

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

lib/index.js

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,33 @@ function mapResponseHeaders(event, context, result) {
238238
return headers;
239239
}
240240

241+
// in V2
242+
// https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html
243+
// if there is no statusCode but valid JSON, API gateway will interpret
244+
// the response.
245+
function translateLambdaResultIfNeeded(result, isV1) {
246+
if (isV1) {
247+
return result || {};
248+
}
249+
250+
if (result && result.statusCode) {
251+
return result;
252+
}
253+
254+
if (!result.statusCode && (typeof result === 'object' || typeof result === 'string')) {
255+
return {
256+
"isBase64Encoded": false,
257+
"statusCode": 200,
258+
"body": JSON.stringify(result),
259+
"headers": {
260+
"content-type": "application/json"
261+
}
262+
}
263+
}
264+
265+
return result || {};
266+
}
267+
241268
function constructBaseLogData(
242269
event,
243270
context,
@@ -292,7 +319,7 @@ function constructBaseLogData(
292319
event.requestContext.http.sourceIp;
293320
}
294321

295-
logData.request.headers = event.headers || {};
322+
logData.request.headers = Object.assign({}, event.headers || {});
296323
logData.metadata = options.getMetadata(event, context);
297324

298325
if (options.logBody && event.body) {
@@ -312,7 +339,8 @@ function constructBaseLogData(
312339
"created request: \n" + JSON.stringify(logData.request)
313340
);
314341

315-
var safeRes = result || {};
342+
var safeRes = translateLambdaResultIfNeeded(result, isV1);
343+
316344
logData.response.time = Math.max(
317345
new Date(logData.request.time).getTime(),
318346
Date.now()

0 commit comments

Comments
 (0)