33 * SPDX-License-Identifier: Apache-2.0
44 */
55
6- import type { ApiQueryParams , ApiRequestBody } from './types' ;
7- import type { ApiMethod } from './types' ;
6+ import type { ApiMethod , ApiQueryParams , ApiRequestBody } from './types' ;
87
98export function buildRequestUrl ( { baseUrl, path, query } : { baseUrl : string ; path : string ; query ?: ApiQueryParams } ) {
109 const url = `${ baseUrl . replace ( / \/ + $ / , '' ) } ${ path } ` ;
@@ -27,21 +26,24 @@ export function buildRequestUrl({ baseUrl, path, query }: { baseUrl: string; pat
2726}
2827
2928export function buildRequestInit ( { method, body } : { method : ApiMethod ; body ?: ApiRequestBody } ) {
30- const headers = new Headers ( { Accept : 'application/json' } ) ;
29+ const headers = new Headers ( ) ;
30+
31+ let requestBody : FormData | string | undefined ;
3132
3233 if ( body ) {
33- headers . set ( 'Content-Type' , 'application/json' ) ;
34+ if ( body instanceof FormData ) {
35+ requestBody = body ;
36+ } else {
37+ headers . set ( 'Content-Type' , 'application/json' ) ;
3438
35- return {
36- method,
37- headers,
38- body : JSON . stringify ( body ) ,
39- } ;
39+ requestBody = JSON . stringify ( body ) ;
40+ }
4041 }
4142
4243 return {
4344 method,
4445 headers,
46+ body : requestBody ,
4547 } ;
4648}
4749
@@ -53,7 +55,10 @@ export async function safeReadText(response: Response) {
5355 }
5456}
5557
56- export function parseBodyText ( bodyText : string | null ) : {
58+ export function parseBodyText (
59+ bodyText : string | null ,
60+ headers : Headers ,
61+ ) : {
5762 data : unknown ;
5863 error ?: Error ;
5964} {
@@ -63,14 +68,23 @@ export function parseBodyText(bodyText: string | null): {
6368 } ;
6469 }
6570
66- try {
67- return {
68- data : JSON . parse ( bodyText ) ,
69- } ;
70- } catch ( error ) {
71- return {
72- data : null ,
73- error : error instanceof Error ? error : new Error ( 'Failed to parse body text.' ) ,
74- } ;
71+ const contentType = headers . get ( 'content-type' ) ?? '' ;
72+ const isJsonResponse = contentType . includes ( 'application/json' ) ;
73+
74+ if ( isJsonResponse ) {
75+ try {
76+ return {
77+ data : JSON . parse ( bodyText ) ,
78+ } ;
79+ } catch ( error ) {
80+ return {
81+ data : null ,
82+ error : error instanceof Error ? error : new Error ( 'Failed to parse body text.' ) ,
83+ } ;
84+ }
7585 }
86+
87+ return {
88+ data : bodyText ,
89+ } ;
7690}
0 commit comments