fix(ui): fetch details parsing

This commit is contained in:
Shekar Siri 2023-11-07 11:28:40 +01:00
parent 08808cf89e
commit 4f0f3cceaf

View file

@ -9,43 +9,63 @@ const REQUEST = 'REQUEST';
const RESPONSE = 'RESPONSE'; const RESPONSE = 'RESPONSE';
const TABS = [HEADERS, REQUEST, RESPONSE].map((tab) => ({ text: tab, key: tab })); const TABS = [HEADERS, REQUEST, RESPONSE].map((tab) => ({ text: tab, key: tab }));
type RequestResponse = {
headers?: Record<string, string>;
body?: any;
};
function parseRequestResponse( function parseRequestResponse(
r: string, r: string,
setHeaders: (hs: Record<string, string> | null) => void, setHeaders: (hs: Record<string, string> | null) => void,
setJSONBody: (body: Record<string, string> | null) => void, setJSONBody: (body: Record<string, unknown> | null) => void,
setStringBody: (body: string) => void, setStringBody: (body: string) => void,
) { ): void {
try { try {
if (!r) { if (!r) {
setHeaders(null); setHeaders(null);
setJSONBody(null); setJSONBody(null);
setStringBody('');
return; return;
} }
const json = JSON.parse(r)
const hs = json.headers
const bd = json.body as string
if (typeof hs === "object") { let parsed: RequestResponse;
setHeaders(hs); try {
parsed = JSON.parse(r);
} catch (e) {
logger.error("Error parsing request string as JSON:", e);
setHeaders(null);
setJSONBody(null);
return;
}
const { headers, body } = parsed;
// Set headers if headers is a non-null object and not an array.
if (headers && typeof headers === "object" && !Array.isArray(headers)) {
setHeaders(headers);
} else { } else {
setHeaders(null); setHeaders(null);
} }
if (!bd) {
setJSONBody(null) // If body is not present, set it as null for JSON and an empty string for string body.
setStringBody('') if (body === undefined || body === null) {
} setJSONBody(null);
try { setStringBody('');
const jBody = JSON.parse(bd) } else if (typeof body === "string") {
if (typeof jBody === "object" && jBody != null) { // Try to parse the body as JSON, if it fails, set it as a string body.
setJSONBody(jBody) try {
} else { const jBody = JSON.parse(body);
setStringBody(bd) setJSONBody(jBody);
} catch {
setStringBody(body);
} }
} catch { } else {
setStringBody(bd) // If body is an object but not a string, it's already in JSON format.
setJSONBody(body as Record<string, unknown>);
} }
} catch(e) { logger.error("Error decoding payload json:", e, r)} } catch (e) {
logger.error("Error decoding payload json:", e, r);
}
} }
@ -137,7 +157,7 @@ function FetchTabs({ resource }: Props) {
<div className="mt-6"> <div className="mt-6">
{ jsonResponse { jsonResponse
? <JSONTree src={jsonResponse} collapsed={false} enableClipboard /> ? <JSONTree src={jsonResponse} collapsed={false} enableClipboard />
: <div className="ml-3 break-words my-3"> {stringResponse} </div> : <div className="ml-3 break-words my-3"></div>
} }
</div> </div>
<div className="divider" /> <div className="divider" />