@@ -21,6 +21,13 @@ const isType = require('type-is')
21
21
function getPathWithQueryStringParams ( event ) {
22
22
return url . format ( { pathname : event . path , query : event . queryStringParameters } )
23
23
}
24
+ function getEventBody ( event ) {
25
+ return Buffer . from ( event . body , event . isBase64Encoded ? 'base64' : 'utf8' )
26
+ }
27
+
28
+ function clone ( json ) {
29
+ return JSON . parse ( JSON . stringify ( json ) )
30
+ }
24
31
25
32
function getContentType ( params ) {
26
33
// only compare mime type; ignore encoding part
@@ -32,11 +39,18 @@ function isContentTypeBinaryMimeType (params) {
32
39
}
33
40
34
41
function mapApiGatewayEventToHttpRequest ( event , context , socketPath ) {
35
- const headers = event . headers || { } // NOTE: Mutating event.headers; prefer deep clone of event.headers
36
- const eventWithoutBody = Object . assign ( { } , event )
37
- delete eventWithoutBody . body
42
+ const headers = Object . assign ( { } , event . headers )
38
43
39
- headers [ 'x-apigateway-event' ] = encodeURIComponent ( JSON . stringify ( eventWithoutBody ) )
44
+ // NOTE: API Gateway is not setting Content-Length header on requests even when they have a body
45
+ if ( event . body && ! headers [ 'Content-Length' ] ) {
46
+ const body = getEventBody ( event )
47
+ headers [ 'Content-Length' ] = Buffer . byteLength ( body )
48
+ }
49
+
50
+ const clonedEventWithoutBody = clone ( event )
51
+ delete clonedEventWithoutBody . body
52
+
53
+ headers [ 'x-apigateway-event' ] = encodeURIComponent ( JSON . stringify ( clonedEventWithoutBody ) )
40
54
headers [ 'x-apigateway-context' ] = encodeURIComponent ( JSON . stringify ( context ) )
41
55
42
56
return {
@@ -121,11 +135,9 @@ function forwardRequestToNodeServer (server, event, context, resolver) {
121
135
const requestOptions = mapApiGatewayEventToHttpRequest ( event , context , getSocketPath ( server . _socketPathSuffix ) )
122
136
const req = http . request ( requestOptions , ( response ) => forwardResponseToApiGateway ( server , response , resolver ) )
123
137
if ( event . body ) {
124
- if ( event . isBase64Encoded ) {
125
- event . body = Buffer . from ( event . body , 'base64' )
126
- }
138
+ const body = getEventBody ( event )
127
139
128
- req . write ( event . body )
140
+ req . write ( body )
129
141
}
130
142
131
143
req . on ( 'error' , ( error ) => forwardConnectionErrorResponseToApiGateway ( error , resolver ) )
0 commit comments