72 lines
2.7 KiB
Python
72 lines
2.7 KiB
Python
import json
|
|
from ..parser.models import ParsedCurl
|
|
|
|
|
|
def generate_javascript(parsed: ParsedCurl) -> str:
|
|
"""Generate JavaScript fetch code from parsed curl command."""
|
|
lines = [
|
|
"async function makeRequest() {",
|
|
f' const url = "{parsed.url}";',
|
|
"",
|
|
]
|
|
|
|
headers_obj = {h.key: h.value for h in parsed.headers}
|
|
if parsed.user_agent:
|
|
headers_obj["User-Agent"] = parsed.user_agent
|
|
|
|
method_name = parsed.method.value.lower()
|
|
|
|
if parsed.data:
|
|
if parsed.data.data_type.value == "json":
|
|
lines.append(f" const jsonData = {json.dumps(parsed.data.json_data, indent=4)};")
|
|
lines.append("")
|
|
lines.append(" const response = await fetch(url, {")
|
|
lines.append(f' method: "{parsed.method.value}"')
|
|
if headers_obj:
|
|
lines.append(" headers: {")
|
|
for key, value in headers_obj.items():
|
|
lines.append(f' "{key}": "{value}",')
|
|
lines.append(' "Content-Type": "application/json"')
|
|
else:
|
|
lines.append(' headers: { "Content-Type": "application/json" },')
|
|
lines.append(" body: JSON.stringify(jsonData)")
|
|
lines.append(" });")
|
|
else:
|
|
lines.append(f" const body = {repr(parsed.data.content)};")
|
|
lines.append("")
|
|
lines.append(" const response = await fetch(url, {")
|
|
lines.append(f' method: "{parsed.method.value}"')
|
|
if headers_obj:
|
|
lines.append(" headers: {")
|
|
for key, value in headers_obj.items():
|
|
lines.append(f' "{key}": "{value}",')
|
|
lines.append(" },")
|
|
lines.append(f" body: body")
|
|
lines.append(" });")
|
|
else:
|
|
lines.append(" const response = await fetch(url, {")
|
|
lines.append(f' method: "{parsed.method.value}"')
|
|
if headers_obj:
|
|
lines.append(",")
|
|
lines.append(" headers: {")
|
|
for key, value in headers_obj.items():
|
|
lines.append(f' "{key}": "{value}",')
|
|
lines.append(" }")
|
|
lines.append(" });")
|
|
|
|
lines.extend([
|
|
"",
|
|
" if (!response.ok) {",
|
|
' throw new Error(`HTTP error! status: ${response.status}`);',
|
|
" }",
|
|
"",
|
|
" const data = await response.json();",
|
|
" console.log(data);",
|
|
" return data;",
|
|
"}",
|
|
"",
|
|
"makeRequest().catch(console.error);",
|
|
])
|
|
|
|
return "\n".join(lines)
|