Skip to content

Commit 40c1c20

Browse files
feat(lenses): enhance content type detection and lens selection logic (hoppscotch#5081)
Co-authored-by: jamesgeorge007 <[email protected]>
1 parent fea6d8c commit 40c1c20

File tree

1 file changed

+44
-8
lines changed
  • packages/hoppscotch-common/src/helpers/lenses

1 file changed

+44
-8
lines changed

packages/hoppscotch-common/src/helpers/lenses/lenses.ts

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,18 +43,54 @@ export function getSuitableLenses(response: HoppRESTResponse): Lens[] {
4343
(h) => h.key.toLowerCase() === "content-type"
4444
)
4545

46+
// If no content type is found, return raw lens as fallback
4647
if (!contentType) return [rawLens]
4748

48-
// Check if the response content type includes `text/plain` and the body contains valid JSON
49-
if (
50-
contentType.value.includes("text/plain") &&
51-
response.type === "success" &&
52-
isValidJSONResponse(response.body)
53-
) {
54-
// Append JSON lens to the list of lenses
55-
return [rawLens, jsonLens]
49+
// For successful responses, use a smarter approach
50+
if (response.type === "success") {
51+
// First, get lenses that match the content type
52+
const matchingLenses = lenses.filter((lens) =>
53+
lens.isSupportedContentType(contentType.value)
54+
)
55+
56+
// For text-based content types, check if content can be parsed as other formats
57+
const isTextBased =
58+
contentType.value.includes("text/") ||
59+
contentType.value.includes("application/javascript") ||
60+
contentType.value.includes("application/xml") ||
61+
contentType.value.includes("application/xhtml+xml") ||
62+
htmlLens.isSupportedContentType(contentType.value)
63+
64+
if (isTextBased && response.body) {
65+
// Check if content is valid JSON
66+
if (
67+
isValidJSONResponse(response.body) &&
68+
!matchingLenses.includes(jsonLens)
69+
) {
70+
// Add JSON lens as an additional option, but keep it after the original content type lens
71+
// This ensures the original content type lens is selected by default
72+
matchingLenses.push(jsonLens)
73+
}
74+
75+
// Add other content type detection here if needed
76+
// e.g., check if content is valid XML, HTML, etc.
77+
}
78+
79+
// If no matching lenses found, include all lenses to give user full control
80+
if (matchingLenses.length === 0) {
81+
return lenses
82+
}
83+
84+
// Always include raw lens for viewing the raw response
85+
if (!matchingLenses.includes(rawLens)) {
86+
matchingLenses.push(rawLens)
87+
}
88+
89+
// Return matching lenses plus raw lens
90+
return matchingLenses
5691
}
5792

93+
// For other response types, use the standard content type detection
5894
const result = []
5995
for (const lens of lenses) {
6096
if (lens.isSupportedContentType(contentType.value)) result.push(lens)

0 commit comments

Comments
 (0)