From 4f0f3cceaf9de8ab815e52a7c3dc1fe882acf6b7 Mon Sep 17 00:00:00 2001 From: Shekar Siri Date: Tue, 7 Nov 2023 11:28:40 +0100 Subject: [PATCH] fix(ui): fetch details parsing --- .../components/FetchTabs/FetchTabs.tsx | 64 ++++++++++++------- 1 file changed, 42 insertions(+), 22 deletions(-) diff --git a/frontend/app/components/shared/FetchDetailsModal/components/FetchTabs/FetchTabs.tsx b/frontend/app/components/shared/FetchDetailsModal/components/FetchTabs/FetchTabs.tsx index 3816af1bc..fedcca070 100644 --- a/frontend/app/components/shared/FetchDetailsModal/components/FetchTabs/FetchTabs.tsx +++ b/frontend/app/components/shared/FetchDetailsModal/components/FetchTabs/FetchTabs.tsx @@ -9,43 +9,63 @@ const REQUEST = 'REQUEST'; const RESPONSE = 'RESPONSE'; const TABS = [HEADERS, REQUEST, RESPONSE].map((tab) => ({ text: tab, key: tab })); + +type RequestResponse = { + headers?: Record; + body?: any; +}; + function parseRequestResponse( r: string, setHeaders: (hs: Record | null) => void, - setJSONBody: (body: Record | null) => void, + setJSONBody: (body: Record | null) => void, setStringBody: (body: string) => void, -) { +): void { try { if (!r) { setHeaders(null); setJSONBody(null); - setStringBody(''); return; } - const json = JSON.parse(r) - const hs = json.headers - const bd = json.body as string - if (typeof hs === "object") { - setHeaders(hs); + let parsed: RequestResponse; + 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 { setHeaders(null); } - if (!bd) { - setJSONBody(null) - setStringBody('') - } - try { - const jBody = JSON.parse(bd) - if (typeof jBody === "object" && jBody != null) { - setJSONBody(jBody) - } else { - setStringBody(bd) + + // If body is not present, set it as null for JSON and an empty string for string body. + if (body === undefined || body === null) { + setJSONBody(null); + setStringBody(''); + } else if (typeof body === "string") { + // Try to parse the body as JSON, if it fails, set it as a string body. + try { + const jBody = JSON.parse(body); + setJSONBody(jBody); + } catch { + setStringBody(body); } - } catch { - setStringBody(bd) + } else { + // If body is an object but not a string, it's already in JSON format. + setJSONBody(body as Record); } - } 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) {
{ jsonResponse ? - :
{stringResponse}
+ :
}