Format XML responses

This commit is contained in:
Gregory Schier
2024-02-22 01:00:02 -08:00
parent ca4d9b1ad6
commit 321b013ce6
5 changed files with 40 additions and 6 deletions

View File

@@ -174,8 +174,6 @@ export const ResponsePane = memo(function ResponsePane({ style, className, activ
) : contentType?.match(/csv|tab-separated/) ? (
<CsvViewer className="pb-2" response={activeResponse} />
) : (
// ) : contentType?.startsWith('application/json') ? (
// <JsonViewer response={activeResponse} />
<TextViewer response={activeResponse} pretty={viewMode === 'pretty'} />
)}
</TabContent>

View File

@@ -6,7 +6,7 @@ import { useFilterResponse } from '../../hooks/useFilterResponse';
import { useResponseBodyText } from '../../hooks/useResponseBodyText';
import { useResponseContentType } from '../../hooks/useResponseContentType';
import { useToggle } from '../../hooks/useToggle';
import { tryFormatJson } from '../../lib/formatters';
import { tryFormatJson, tryFormatXml } from '../../lib/formatters';
import type { HttpResponse } from '../../lib/models';
import { Editor } from '../core/Editor';
import { IconButton } from '../core/IconButton';
@@ -23,7 +23,12 @@ export function TextViewer({ response, pretty }: Props) {
const contentType = useResponseContentType(response);
const rawBody = useResponseBodyText(response) ?? '';
const formattedBody = pretty && contentType?.includes('json') ? tryFormatJson(rawBody) : rawBody;
const formattedBody =
pretty && contentType?.includes('json')
? tryFormatJson(rawBody)
: pretty && contentType?.includes('xml')
? tryFormatXml(rawBody)
: rawBody;
const filteredResponse = useFilterResponse({ filter: filterText, responseId: response.id });
const body = filteredResponse ?? formattedBody;

View File

@@ -1,3 +1,5 @@
import xmlFormat from 'xml-formatter';
export function tryFormatJson(text: string, pretty = true): string {
try {
if (pretty) return JSON.stringify(JSON.parse(text), null, 2);
@@ -6,3 +8,11 @@ export function tryFormatJson(text: string, pretty = true): string {
return text;
}
}
export function tryFormatXml(text: string): string {
try {
return xmlFormat(text, { throwOnFailure: true, strictMode: false });
} catch (_) {
return text;
}
}