feat: format JSON responses having text/plain content type (#4916)

Co-authored-by: jamesgeorge007 <25279263+jamesgeorge007@users.noreply.github.com>
This commit is contained in:
Anwarul Islam 2025-03-28 14:08:32 +06:00 committed by GitHub
parent 4e29810f69
commit 9e541a8a4b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 37 additions and 2 deletions

View file

@ -1,6 +1,31 @@
import { defineAsyncComponent } from "vue"
import { isJSONContentType } from "../utils/contenttypes"
import { Lens } from "./lenses"
import { isJSONContentType } from "../utils/contenttypes"
/**
* Checks if response body contents can be parsed as valid JSON
*/
export function isValidJSONResponse(contents: string | ArrayBuffer): boolean {
if (!contents) {
return false
}
const resolvedStr =
contents instanceof ArrayBuffer
? new TextDecoder("utf-8").decode(contents)
: contents
if (!resolvedStr.trim()) {
return false
}
try {
JSON.parse(resolvedStr)
return true
} catch (e) {
return false
}
}
const jsonLens: Lens = {
lensName: "response.json",

View file

@ -1,5 +1,5 @@
import { HoppRESTResponse } from "../types/HoppRESTResponse"
import jsonLens from "./jsonLens"
import jsonLens, { isValidJSONResponse } from "./jsonLens"
import rawLens from "./rawLens"
import imageLens from "./imageLens"
import htmlLens from "./htmlLens"
@ -45,6 +45,16 @@ export function getSuitableLenses(response: HoppRESTResponse): Lens[] {
if (!contentType) return [rawLens]
// Check if the response content type includes `text/plain` and the body contains valid JSON
if (
contentType.value.includes("text/plain") &&
response.type === "success" &&
isValidJSONResponse(response.body)
) {
// Append JSON lens to the list of lenses
return [rawLens, jsonLens]
}
const result = []
for (const lens of lenses) {
if (lens.isSupportedContentType(contentType.value)) result.push(lens)