Initial commit: Add curl-to-code-cli project
This commit is contained in:
71
.curl_to_code/generators/javascript_gen.py
Normal file
71
.curl_to_code/generators/javascript_gen.py
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
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)
|
||||||
Reference in New Issue
Block a user