File tree 2 files changed +30
-15
lines changed
2 files changed +30
-15
lines changed Original file line number Diff line number Diff line change @@ -146,34 +146,30 @@ export default async function fetchWrapper(
146
146
return octokitResponse ;
147
147
}
148
148
149
- function getResponseData ( response : Response ) : Promise < any > {
149
+ async function getResponseData ( response : Response ) : Promise < any > {
150
150
const contentType = response . headers . get ( "content-type" ) ;
151
151
152
152
if ( ! contentType ) {
153
- return response . text ( ) ;
153
+ return response . text ( ) . catch ( ( ) => "" ) ;
154
154
}
155
155
156
156
const mimetype = safeParse ( contentType ) ;
157
157
158
158
if ( mimetype . type === "application/json" ) {
159
- return (
160
- response
161
- . json ( )
162
- // In the event that we get an empty response body we fallback to
163
- // using .text(), but this should be investigated since if this were
164
- // to occur in the GitHub API it really should not return an empty body.
165
- . catch ( ( ) => response . text ( ) )
166
- // `node-fetch` is throwing a "body used already for" error if `.text()` is run
167
- // after a failed .json(). To account for that we fallback to an empty string
168
- . catch ( ( ) => "" )
169
- ) ;
159
+ let text = "" ;
160
+ try {
161
+ text = await response . text ( ) ;
162
+ return JSON . parse ( text ) ;
163
+ } catch ( err ) {
164
+ return text ;
165
+ }
170
166
} else if (
171
167
mimetype . type . startsWith ( "text/" ) ||
172
168
mimetype . parameters . charset ?. toLowerCase ( ) === "utf-8"
173
169
) {
174
- return response . text ( ) ;
170
+ return response . text ( ) . catch ( ( ) => "" ) ;
175
171
} else {
176
- return response . arrayBuffer ( ) ;
172
+ return response . arrayBuffer ( ) . catch ( ( ) => new ArrayBuffer ( 0 ) ) ;
177
173
}
178
174
}
179
175
Original file line number Diff line number Diff line change @@ -1397,4 +1397,23 @@ x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
1397
1397
1398
1398
request . closeMockServer ( ) ;
1399
1399
} ) ;
1400
+
1401
+ it ( "invalid json as response data" , async ( ) => {
1402
+ expect . assertions ( 4 ) ;
1403
+
1404
+ const request = await mockRequestHttpServer ( async ( req , res ) => {
1405
+ expect ( req . method ) . toBe ( "GET" ) ;
1406
+ expect ( req . url ) . toBe ( "/" ) ;
1407
+
1408
+ res . writeHead ( 200 , {
1409
+ "content-type" : "application/json" ,
1410
+ } ) ;
1411
+ res . end ( '"invalid' ) ;
1412
+ } ) ;
1413
+
1414
+ const response = await request ( "GET /" ) ;
1415
+
1416
+ expect ( response . status ) . toEqual ( 200 ) ;
1417
+ expect ( response . data ) . toEqual ( '"invalid' ) ;
1418
+ } ) ;
1400
1419
} ) ;
You can’t perform that action at this time.
0 commit comments