@@ -20,38 +20,62 @@ const app = new App(manifest);
20
20
* @param {Context } context
21
21
*/
22
22
export async function index ( context ) {
23
+ const request = toRequest ( context ) ;
24
+
25
+ if ( debug ) {
26
+ context . log ( `Request: ${ JSON . stringify ( request ) } ` ) ;
27
+ }
28
+
29
+ const rendered = await app . render ( request ) ;
30
+ const response = await toResponse ( rendered ) ;
31
+
32
+ if ( debug ) {
33
+ context . log ( `Response: ${ JSON . stringify ( response ) } ` ) ;
34
+ }
35
+
36
+ context . res = response ;
37
+ }
38
+
39
+ /**
40
+ * @param {Context } context
41
+ * @returns {Request }
42
+ * */
43
+ function toRequest ( context ) {
23
44
const { method, headers, rawBody : body } = context . req ;
24
45
// because we proxy all requests to the render function, the original URL in the request is /api/__render
25
46
// this header contains the URL the user requested
26
47
const originalUrl = headers [ 'x-ms-original-url' ] ;
27
- const url = new URL ( originalUrl ) ;
28
48
29
- const rawBody = typeof body === 'string' ? Buffer . from ( body , 'utf-8' ) : body ;
30
- const request = {
31
- url,
49
+ /** @type {RequestInit } */
50
+ const init = {
32
51
method,
33
- headers,
34
- rawBody
52
+ headers : new Headers ( headers )
35
53
} ;
36
54
37
- if ( debug ) {
38
- context . log ( `Request: ${ JSON . stringify ( request ) } ` ) ;
55
+ if ( method !== 'GET' && method !== 'HEAD' ) {
56
+ init . body = typeof body === 'string' ? Buffer . from ( body , 'utf-8' ) : body ;
39
57
}
40
58
41
- const rendered = await app . render ( request ) ;
59
+ return new Request ( originalUrl , init ) ;
60
+ }
61
+
62
+ /**
63
+ * @param {Response } rendered
64
+ * @returns {Promise<Record<string, any>> }
65
+ */
66
+ async function toResponse ( rendered ) {
67
+ const { status } = rendered ;
68
+ const resBody = await rendered . text ( ) ;
42
69
43
- const { status, headers : resHeaders , body : resBody } = rendered ;
70
+ /** @type {Record<string, string> } */
71
+ const resHeaders = { } ;
72
+ rendered . headers . forEach ( ( value , key ) => {
73
+ resHeaders [ key ] = value ;
74
+ } ) ;
44
75
45
- const response = {
76
+ return {
46
77
status,
47
78
body : resBody ,
48
- headers : resHeaders ,
49
- rawBody
79
+ headers : resHeaders
50
80
} ;
51
-
52
- if ( debug ) {
53
- context . log ( `Response: ${ JSON . stringify ( response ) } ` ) ;
54
- }
55
-
56
- context . res = response ;
57
81
}
0 commit comments