Refactor APIRequest class to use 'body' instead of 'record' parameter

This commit is contained in:
Rodrigo Nader 2024-03-06 00:50:27 -03:00
commit 9958ce76fd

View file

@ -27,9 +27,9 @@ class APIRequest(CustomComponent):
"display_name": "Headers", "display_name": "Headers",
"info": "The headers to send with the request.", "info": "The headers to send with the request.",
}, },
"record": { "body": {
"display_name": "Record", "display_name": "Body",
"info": "The record to send with the request (for POST, PATCH, PUT).", "info": "The body to send with the request (for POST, PATCH, PUT).",
}, },
"timeout": { "timeout": {
"display_name": "Timeout", "display_name": "Timeout",
@ -45,14 +45,14 @@ class APIRequest(CustomComponent):
method: str, method: str,
url: str, url: str,
headers: Optional[dict] = None, headers: Optional[dict] = None,
record: Optional[Record] = None, body: Optional[dict] = None,
timeout: int = 5, timeout: int = 5,
) -> Record: ) -> Record:
method = method.upper() method = method.upper()
if method not in ["GET", "POST", "PATCH", "PUT"]: if method not in ["GET", "POST", "PATCH", "PUT"]:
raise ValueError(f"Unsupported method: {method}") raise ValueError(f"Unsupported method: {method}")
data = record.data if record else None data = body if body else None
try: try:
response = await client.request( response = await client.request(
method, url, headers=headers, content=data, timeout=timeout method, url, headers=headers, content=data, timeout=timeout
@ -86,22 +86,22 @@ class APIRequest(CustomComponent):
method: str, method: str,
url: List[str], url: List[str],
headers: Optional[dict] = None, headers: Optional[dict] = None,
record: Optional[Record] = None, body: Optional[dict] = None,
timeout: int = 5, timeout: int = 5,
) -> List[Record]: ) -> List[Record]:
if headers is None: if headers is None:
headers = {} headers = {}
urls = url if isinstance(url, list) else [url] urls = url if isinstance(url, list) else [url]
records = ( bodies = (
record body
if isinstance(record, list) if isinstance(body, list)
else [record] if record else [None] * len(urls) else [body] if body else [None] * len(urls)
) )
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
results = await asyncio.gather( results = await asyncio.gather(
*[ *[
self.make_request(client, method, u, headers, rec, timeout) self.make_request(client, method, u, headers, rec, timeout)
for u, rec in zip(urls, records) for u, rec in zip(urls, bodies)
] ]
) )
return results return results