@@ -8,11 +8,12 @@ const isStringTuple = (_: [string, unknown]): _ is [string, string] =>
8
8
/**
9
9
* Get DCR content from a `theguardian.com` URL.
10
10
* Takes in optional `X-Gu-*` headers to send.
11
+ * Returns the parsed JSON config and any cookies set by the request.
11
12
*/
12
13
async function getContentFromURL (
13
14
url : URL ,
14
15
_headers : IncomingHttpHeaders ,
15
- ) : Promise < unknown > {
16
+ ) : Promise < { config : unknown ; cookies : string [ ] } > {
16
17
// searchParams will only work for the first set of query params because 'url' is already a query param itself
17
18
const searchparams = url . searchParams . toString ( ) ;
18
19
@@ -30,10 +31,13 @@ async function getContentFromURL(
30
31
. filter ( isStringTuple ) ,
31
32
) ;
32
33
33
- // pick all the keys from the JSON except `html`
34
- // eslint-disable-next-line @typescript-eslint/no-unused-vars -- we don't want `html` in the config
35
- const { html, ...config } = await fetch ( jsonUrl , { headers } )
36
- . then ( ( response ) => response . json ( ) )
34
+ const { cookies, json } = await fetch ( jsonUrl , { headers } )
35
+ . then ( async ( response ) => {
36
+ return {
37
+ json : ( await response . json ( ) ) as unknown ,
38
+ cookies : response . headers . getSetCookie ( ) ,
39
+ } ;
40
+ } )
37
41
. catch ( ( error ) => {
38
42
if ( isObject ( error ) && error . type === 'invalid-json' ) {
39
43
throw new Error (
@@ -43,7 +47,11 @@ async function getContentFromURL(
43
47
throw error ;
44
48
} ) ;
45
49
46
- return config ;
50
+ // pick all the keys from the JSON except `html`
51
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- we don't want `html` in the config
52
+ const { html, ...config } = json as Record < string , unknown > ;
53
+
54
+ return { config, cookies } ;
47
55
}
48
56
49
57
/**
@@ -65,8 +73,14 @@ export const getContentFromURLMiddleware: Handler = async (req, res, next) => {
65
73
const url = new URL (
66
74
'https://www.theguardian.com/crosswords/digital-edition' ,
67
75
) ;
68
- const content = await getContentFromURL ( url , req . headers ) ;
69
- req . body = content ;
76
+ const { config, cookies } = await getContentFromURL (
77
+ url ,
78
+ req . headers ,
79
+ ) ;
80
+ req . body = config ;
81
+ for ( const cookie of cookies ) {
82
+ res . append ( 'Set-Cookie' , cookie ) ;
83
+ }
70
84
next ( ) ;
71
85
} catch ( error ) {
72
86
console . error ( error ) ;
@@ -88,7 +102,14 @@ export const getContentFromURLMiddleware: Handler = async (req, res, next) => {
88
102
}
89
103
90
104
try {
91
- req . body = await getContentFromURL ( sourceURL , req . headers ) ;
105
+ const { config, cookies } = await getContentFromURL (
106
+ sourceURL ,
107
+ req . headers ,
108
+ ) ;
109
+ req . body = config ;
110
+ for ( const cookie of cookies ) {
111
+ res . append ( 'Set-Cookie' , cookie ) ;
112
+ }
92
113
} catch ( error ) {
93
114
console . error ( error ) ;
94
115
next ( error ) ;
0 commit comments