@@ -9,19 +9,60 @@ type HttpRequestResult =
99 | { success : true ; data : unknown ; status : number }
1010 | { success : false ; error : string ; status ?: number } ;
1111
12+ function parseHeaders ( httpHeaders ?: string ) : Record < string , string > {
13+ if ( ! httpHeaders ) {
14+ return { } ;
15+ }
16+ try {
17+ return JSON . parse ( httpHeaders ) ;
18+ } catch {
19+ return { } ;
20+ }
21+ }
22+
23+ function parseBody ( httpMethod : string , httpBody ?: string ) : string | undefined {
24+ if ( httpMethod === "GET" || ! httpBody ) {
25+ return ;
26+ }
27+ try {
28+ const parsedBody = JSON . parse ( httpBody ) ;
29+ return Object . keys ( parsedBody ) . length > 0
30+ ? JSON . stringify ( parsedBody )
31+ : undefined ;
32+ } catch {
33+ const trimmed = httpBody . trim ( ) ;
34+ return trimmed && trimmed !== "{}" ? httpBody : undefined ;
35+ }
36+ }
37+
38+ function parseResponse ( response : Response ) : Promise < unknown > {
39+ const contentType = response . headers . get ( "content-type" ) ;
40+ if ( contentType ?. includes ( "application/json" ) ) {
41+ return response . json ( ) ;
42+ }
43+ return response . text ( ) ;
44+ }
45+
1246export async function httpRequestStep ( input : {
13- url : string ;
14- method : string ;
15- headers : Record < string , string > ;
16- body : unknown ;
47+ endpoint : string ;
48+ httpMethod : string ;
49+ httpHeaders ?: string ;
50+ httpBody ?: string ;
1751} ) : Promise < HttpRequestResult > {
1852 "use step" ;
1953
54+ if ( ! input . endpoint ) {
55+ return {
56+ success : false ,
57+ error : "HTTP request failed: URL is required" ,
58+ } ;
59+ }
60+
2061 try {
21- const response = await fetch ( input . url , {
22- method : input . method ,
23- headers : input . headers ,
24- body : input . body ? JSON . stringify ( input . body ) : undefined ,
62+ const response = await fetch ( input . endpoint , {
63+ method : input . httpMethod ,
64+ headers : parseHeaders ( input . httpHeaders ) ,
65+ body : parseBody ( input . httpMethod , input . httpBody ) ,
2566 } ) ;
2667
2768 if ( ! response . ok ) {
@@ -33,7 +74,7 @@ export async function httpRequestStep(input: {
3374 } ;
3475 }
3576
36- const data = await response . json ( ) ;
77+ const data = await parseResponse ( response ) ;
3778 return { success : true , data, status : response . status } ;
3879 } catch ( error ) {
3980 return {
0 commit comments