@@ -10,33 +10,32 @@ export function init(manifest) {
10
10
const server = new Server ( manifest ) ;
11
11
12
12
return async ( event , context ) => {
13
- const rendered = await server . respond ( to_request ( event ) , {
13
+ const response = await server . respond ( to_request ( event ) , {
14
14
platform : { context } ,
15
15
getClientAddress ( ) {
16
16
return event . headers [ 'x-nf-client-connection-ip' ] ;
17
17
}
18
18
} ) ;
19
19
20
20
const partial_response = {
21
- statusCode : rendered . status ,
22
- ...split_headers ( rendered . headers )
21
+ statusCode : response . status ,
22
+ ...split_headers ( response . headers )
23
23
} ;
24
24
25
- // TODO this is probably wrong now?
26
- if ( rendered . body instanceof Uint8Array ) {
25
+ if ( ! is_text ( response . headers . get ( 'content-type' ) ) ) {
27
26
// Function responses should be strings (or undefined), and responses with binary
28
27
// content should be base64 encoded and set isBase64Encoded to true.
29
28
// https://github.com/netlify/functions/blob/main/src/function/response.ts
30
29
return {
31
30
...partial_response ,
32
31
isBase64Encoded : true ,
33
- body : Buffer . from ( rendered . body ) . toString ( 'base64' )
32
+ body : Buffer . from ( await response . arrayBuffer ( ) ) . toString ( 'base64' )
34
33
} ;
35
34
}
36
35
37
36
return {
38
37
...partial_response ,
39
- body : await rendered . text ( )
38
+ body : await response . text ( )
40
39
} ;
41
40
} ;
42
41
}
@@ -61,3 +60,23 @@ function to_request(event) {
61
60
62
61
return new Request ( rawUrl , init ) ;
63
62
}
63
+
64
+ const text_types = new Set ( [
65
+ 'application/xml' ,
66
+ 'application/json' ,
67
+ 'application/x-www-form-urlencoded' ,
68
+ 'multipart/form-data'
69
+ ] ) ;
70
+
71
+ /**
72
+ * Decides how the body should be parsed based on its mime type
73
+ *
74
+ * @param {string | undefined | null } content_type The `content-type` header of a request/response.
75
+ * @returns {boolean }
76
+ */
77
+ function is_text ( content_type ) {
78
+ if ( ! content_type ) return true ; // defaults to json
79
+ const type = content_type . split ( ';' ) [ 0 ] . toLowerCase ( ) ; // get the mime type
80
+
81
+ return type . startsWith ( 'text/' ) || type . endsWith ( '+xml' ) || text_types . has ( type ) ;
82
+ }
0 commit comments