mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-07-05 20:41:58 +02:00
Convert request bodies when changing type (#499)
This commit is contained in:
@@ -20,6 +20,7 @@ import { deepEqualAtom } from "../lib/atoms";
|
||||
import { languageFromContentType } from "../lib/contentType";
|
||||
import { generateId } from "../lib/generateId";
|
||||
import { extractPathPlaceholders } from "../lib/pathPlaceholders";
|
||||
import { convertRequestBody } from "../lib/requestBodyConversion";
|
||||
import {
|
||||
BODY_TYPE_BINARY,
|
||||
BODY_TYPE_FORM_MULTIPART,
|
||||
@@ -195,7 +196,14 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
||||
});
|
||||
};
|
||||
|
||||
const patch: Partial<HttpRequest> = { bodyType };
|
||||
const patch: Partial<HttpRequest> = {
|
||||
bodyType,
|
||||
body: convertRequestBody({
|
||||
body: activeRequest.body,
|
||||
fromBodyType: activeRequest.bodyType,
|
||||
toBodyType: bodyType,
|
||||
}),
|
||||
};
|
||||
let newContentType: string | null | undefined;
|
||||
if (bodyType === BODY_TYPE_NONE) {
|
||||
newContentType = null;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { HttpRequest } from "@yaakapp-internal/models";
|
||||
|
||||
import { useAtom } from "jotai";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { useLocalStorage } from "react-use";
|
||||
import { useIntrospectGraphQL } from "../../hooks/useIntrospectGraphQL";
|
||||
import { useStateWithDeps } from "../../hooks/useStateWithDeps";
|
||||
@@ -11,9 +11,13 @@ import type { DropdownItem } from "../core/Dropdown";
|
||||
import { Dropdown } from "../core/Dropdown";
|
||||
import type { EditorProps } from "../core/Editor/Editor";
|
||||
import { Editor } from "../core/Editor/LazyEditor";
|
||||
import type { RadioDropdownItem } from "../core/RadioDropdown";
|
||||
import { RadioDropdown } from "../core/RadioDropdown";
|
||||
import { Banner, FormattedError, Icon } from "@yaakapp-internal/ui";
|
||||
import { Separator } from "../core/Separator";
|
||||
import { tryFormatGraphql } from "../../lib/formatters";
|
||||
import { parseGraphQLOperationNames } from "../../lib/graphqlOperationNames";
|
||||
import { normalizeGraphQLBody } from "../../lib/requestBodyConversion";
|
||||
import { showGraphQLDocExplorerAtom } from "./graphqlAtoms";
|
||||
|
||||
type Props = Pick<EditorProps, "heightMode" | "className" | "forceUpdateKey"> & {
|
||||
@@ -22,6 +26,8 @@ type Props = Pick<EditorProps, "heightMode" | "className" | "forceUpdateKey"> &
|
||||
request: HttpRequest;
|
||||
};
|
||||
|
||||
const OPERATION_NAME_NOT_SPECIFIED = "";
|
||||
|
||||
export function GraphQLEditor(props: Props) {
|
||||
// There's some weirdness with stale onChange being called when switching requests, so we'll
|
||||
// key on the request ID as a workaround for now.
|
||||
@@ -38,25 +44,25 @@ function GraphQLEditorInner({ request, onChange, baseRequest, ...extraEditorProp
|
||||
const [currentBody, setCurrentBody] = useStateWithDeps<{
|
||||
query: string;
|
||||
variables: string | undefined;
|
||||
operationName?: string;
|
||||
}>(() => {
|
||||
// Migrate text bodies to GraphQL format
|
||||
// NOTE: This is how GraphQL used to be stored
|
||||
if ("text" in request.body) {
|
||||
const b = tryParseJson(request.body.text, {});
|
||||
const variables = JSON.stringify(b.variables || undefined, null, 2);
|
||||
return { query: b.query ?? "", variables };
|
||||
}
|
||||
|
||||
return { query: request.body.query ?? "", variables: request.body.variables ?? "" };
|
||||
return normalizeGraphQLBody(request.body);
|
||||
}, [extraEditorProps.forceUpdateKey]);
|
||||
|
||||
const [isDocOpenRecord, setGraphqlDocStateAtomValue] = useAtom(showGraphQLDocExplorerAtom);
|
||||
const isDocOpen = isDocOpenRecord[request.id] !== undefined;
|
||||
const parsedOperationNames = useMemo(
|
||||
() => parseGraphQLOperationNames(currentBody.query),
|
||||
[currentBody.query],
|
||||
);
|
||||
const operationNames = useMemo(() => parsedOperationNames ?? [], [parsedOperationNames]);
|
||||
|
||||
const handleChangeQuery = useCallback(
|
||||
(query: string) => {
|
||||
setCurrentBody(({ variables }) => {
|
||||
const newBody = { query, variables };
|
||||
setCurrentBody(({ variables, operationName }) => {
|
||||
const newBody = buildGraphQLBody({ query, variables, operationName });
|
||||
onChange(newBody);
|
||||
return newBody;
|
||||
});
|
||||
@@ -66,8 +72,8 @@ function GraphQLEditorInner({ request, onChange, baseRequest, ...extraEditorProp
|
||||
|
||||
const handleChangeVariables = useCallback(
|
||||
(variables: string) => {
|
||||
setCurrentBody(({ query }) => {
|
||||
const newBody = { query, variables: variables || undefined };
|
||||
setCurrentBody(({ query, operationName }) => {
|
||||
const newBody = buildGraphQLBody({ query, variables, operationName });
|
||||
onChange(newBody);
|
||||
return newBody;
|
||||
});
|
||||
@@ -75,125 +81,196 @@ function GraphQLEditorInner({ request, onChange, baseRequest, ...extraEditorProp
|
||||
[onChange, setCurrentBody],
|
||||
);
|
||||
|
||||
const handleChangeOperationName = useCallback(
|
||||
(operationName: string) => {
|
||||
setCurrentBody(({ query, variables }) => {
|
||||
const newBody = buildGraphQLBody({ query, variables, operationName });
|
||||
onChange(newBody);
|
||||
return newBody;
|
||||
});
|
||||
},
|
||||
[onChange, setCurrentBody],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (parsedOperationNames == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentBody.operationName === OPERATION_NAME_NOT_SPECIFIED) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentBody.operationName && operationNames.includes(currentBody.operationName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep the saved body aligned with the visible default, so send/copy use the selected operation.
|
||||
const operationName = operationNames[0];
|
||||
if (currentBody.operationName === operationName) {
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentBody(({ query, variables }) => {
|
||||
const newBody = buildGraphQLBody({ query, variables, operationName });
|
||||
onChange(newBody);
|
||||
return newBody;
|
||||
});
|
||||
}, [
|
||||
currentBody.operationName,
|
||||
onChange,
|
||||
operationNames,
|
||||
parsedOperationNames,
|
||||
setCurrentBody,
|
||||
]);
|
||||
|
||||
const actions = useMemo<EditorProps["actions"]>(
|
||||
() => [
|
||||
<div key="actions" className="flex flex-row opacity-100! shadow!">
|
||||
<div key="introspection" className="opacity-100!">
|
||||
{schema === undefined ? null /* Initializing */ : (
|
||||
<Dropdown
|
||||
items={[
|
||||
...((schema != null
|
||||
? [
|
||||
{
|
||||
label: "Clear",
|
||||
onSelect: clear,
|
||||
color: "danger",
|
||||
leftSlot: <Icon icon="trash" />,
|
||||
},
|
||||
{ type: "separator" },
|
||||
]
|
||||
: []) satisfies DropdownItem[]),
|
||||
{
|
||||
hidden: !error,
|
||||
label: (
|
||||
<Banner color="danger">
|
||||
<p className="mb-1">Schema introspection failed</p>
|
||||
<Button
|
||||
size="xs"
|
||||
color="danger"
|
||||
variant="border"
|
||||
onClick={() => {
|
||||
showDialog({
|
||||
title: "Introspection Failed",
|
||||
size: "sm",
|
||||
id: "introspection-failed",
|
||||
render: ({ hide }) => (
|
||||
<>
|
||||
<FormattedError>{error ?? "unknown"}</FormattedError>
|
||||
<div className="w-full my-4">
|
||||
<Button
|
||||
onClick={async () => {
|
||||
hide();
|
||||
await refetch();
|
||||
}}
|
||||
className="ml-auto"
|
||||
color="primary"
|
||||
size="sm"
|
||||
>
|
||||
Retry Request
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
),
|
||||
});
|
||||
}}
|
||||
>
|
||||
View Error
|
||||
</Button>
|
||||
</Banner>
|
||||
),
|
||||
type: "content",
|
||||
},
|
||||
{
|
||||
hidden: schema == null,
|
||||
label: `${isDocOpen ? "Hide" : "Show"} Documentation`,
|
||||
leftSlot: <Icon icon="book_open_text" />,
|
||||
onSelect: () => {
|
||||
setGraphqlDocStateAtomValue((v) => ({
|
||||
...v,
|
||||
[request.id]: isDocOpen ? undefined : null,
|
||||
}));
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Introspect Schema",
|
||||
leftSlot: <Icon icon="refresh" spin={isLoading} />,
|
||||
keepOpenOnSelect: true,
|
||||
onSelect: refetch,
|
||||
},
|
||||
{ type: "separator", label: "Setting" },
|
||||
{
|
||||
label: "Automatic Introspection",
|
||||
keepOpenOnSelect: true,
|
||||
onSelect: () => {
|
||||
setAutoIntrospectDisabled({
|
||||
...autoIntrospectDisabled,
|
||||
[baseRequest.id]: !autoIntrospectDisabled?.[baseRequest.id],
|
||||
});
|
||||
},
|
||||
leftSlot: (
|
||||
<Icon
|
||||
icon={
|
||||
autoIntrospectDisabled?.[baseRequest.id]
|
||||
? "check_square_unchecked"
|
||||
: "check_square_checked"
|
||||
}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="border"
|
||||
title="Refetch Schema"
|
||||
isLoading={isLoading}
|
||||
color={error ? "danger" : "default"}
|
||||
forDropdown
|
||||
>
|
||||
{error ? "Introspection Failed" : schema ? "Schema" : "No Schema"}
|
||||
</Button>
|
||||
</Dropdown>
|
||||
)}
|
||||
operationNames.length > 0 ? (
|
||||
<div key="operation" className="opacity-100!">
|
||||
<RadioDropdown
|
||||
value={currentBody.operationName ?? operationNames[0] ?? OPERATION_NAME_NOT_SPECIFIED}
|
||||
onChange={handleChangeOperationName}
|
||||
items={[
|
||||
{ type: "separator", label: "Operation Name" },
|
||||
{
|
||||
label: <span className="text-text-subtle italic">Not specified</span>,
|
||||
value: OPERATION_NAME_NOT_SPECIFIED,
|
||||
},
|
||||
...operationNames.map((operationName) => ({
|
||||
label: operationName,
|
||||
value: operationName,
|
||||
})),
|
||||
] satisfies RadioDropdownItem<string>[]}
|
||||
>
|
||||
<Button size="sm" variant="border" title="Select Operation" forDropdown>
|
||||
{currentBody.operationName === OPERATION_NAME_NOT_SPECIFIED ? (
|
||||
<span className="text-text-subtle italic">Not specified</span>
|
||||
) : (
|
||||
currentBody.operationName ?? operationNames[0]
|
||||
)}
|
||||
</Button>
|
||||
</RadioDropdown>
|
||||
</div>
|
||||
) : null,
|
||||
<div key="introspection" className="opacity-100!">
|
||||
{schema === undefined ? null /* Initializing */ : (
|
||||
<Dropdown
|
||||
items={[
|
||||
...((schema != null
|
||||
? [
|
||||
{
|
||||
label: "Clear",
|
||||
onSelect: clear,
|
||||
color: "danger",
|
||||
leftSlot: <Icon icon="trash" />,
|
||||
},
|
||||
{ type: "separator" },
|
||||
]
|
||||
: []) satisfies DropdownItem[]),
|
||||
{
|
||||
hidden: !error,
|
||||
label: (
|
||||
<Banner color="danger">
|
||||
<p className="mb-1">Schema introspection failed</p>
|
||||
<Button
|
||||
size="xs"
|
||||
color="danger"
|
||||
variant="border"
|
||||
onClick={() => {
|
||||
showDialog({
|
||||
title: "Introspection Failed",
|
||||
size: "sm",
|
||||
id: "introspection-failed",
|
||||
render: ({ hide }) => (
|
||||
<>
|
||||
<FormattedError>{error ?? "unknown"}</FormattedError>
|
||||
<div className="w-full my-4">
|
||||
<Button
|
||||
onClick={async () => {
|
||||
hide();
|
||||
await refetch();
|
||||
}}
|
||||
className="ml-auto"
|
||||
color="primary"
|
||||
size="sm"
|
||||
>
|
||||
Retry Request
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
),
|
||||
});
|
||||
}}
|
||||
>
|
||||
View Error
|
||||
</Button>
|
||||
</Banner>
|
||||
),
|
||||
type: "content",
|
||||
},
|
||||
{
|
||||
hidden: schema == null,
|
||||
label: `${isDocOpen ? "Hide" : "Show"} Documentation`,
|
||||
leftSlot: <Icon icon="book_open_text" />,
|
||||
onSelect: () => {
|
||||
setGraphqlDocStateAtomValue((v) => ({
|
||||
...v,
|
||||
[request.id]: isDocOpen ? undefined : null,
|
||||
}));
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Introspect Schema",
|
||||
leftSlot: <Icon icon="refresh" spin={isLoading} />,
|
||||
keepOpenOnSelect: true,
|
||||
onSelect: refetch,
|
||||
},
|
||||
{ type: "separator", label: "Setting" },
|
||||
{
|
||||
label: "Automatic Introspection",
|
||||
keepOpenOnSelect: true,
|
||||
onSelect: () => {
|
||||
setAutoIntrospectDisabled({
|
||||
...autoIntrospectDisabled,
|
||||
[baseRequest.id]: !autoIntrospectDisabled?.[baseRequest.id],
|
||||
});
|
||||
},
|
||||
leftSlot: (
|
||||
<Icon
|
||||
icon={
|
||||
autoIntrospectDisabled?.[baseRequest.id]
|
||||
? "check_square_unchecked"
|
||||
: "check_square_checked"
|
||||
}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="border"
|
||||
title="Refetch Schema"
|
||||
isLoading={isLoading}
|
||||
color={error ? "danger" : "default"}
|
||||
forDropdown
|
||||
>
|
||||
{error ? "Introspection Failed" : schema ? "Schema" : "No Schema"}
|
||||
</Button>
|
||||
</Dropdown>
|
||||
)}
|
||||
</div>,
|
||||
],
|
||||
[
|
||||
schema,
|
||||
clear,
|
||||
error,
|
||||
currentBody.operationName,
|
||||
handleChangeOperationName,
|
||||
isDocOpen,
|
||||
isLoading,
|
||||
operationNames,
|
||||
refetch,
|
||||
autoIntrospectDisabled,
|
||||
baseRequest.id,
|
||||
@@ -237,10 +314,23 @@ function GraphQLEditorInner({ request, onChange, baseRequest, ...extraEditorProp
|
||||
);
|
||||
}
|
||||
|
||||
function tryParseJson(text: string, fallback: unknown) {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return fallback;
|
||||
function buildGraphQLBody(body: {
|
||||
query: string;
|
||||
variables: string | undefined;
|
||||
operationName?: string;
|
||||
}) {
|
||||
const result: {
|
||||
query: string;
|
||||
variables: string | undefined;
|
||||
operationName?: string;
|
||||
} = {
|
||||
query: body.query,
|
||||
variables: body.variables || undefined,
|
||||
};
|
||||
|
||||
if (typeof body.operationName === "string") {
|
||||
result.operationName = body.operationName;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { getGraphQLOperationNames, parseGraphQLOperationNames } from "./graphqlOperationNames";
|
||||
|
||||
describe("getGraphQLOperationNames", () => {
|
||||
test("returns named operations from a GraphQL document", () => {
|
||||
expect(
|
||||
getGraphQLOperationNames(`
|
||||
query GetUser { user { id } }
|
||||
mutation UpdateUser { updateUser { id } }
|
||||
subscription UserChanged { userChanged { id } }
|
||||
fragment UserFields on User { id }
|
||||
`),
|
||||
).toEqual(["GetUser", "UpdateUser", "UserChanged"]);
|
||||
});
|
||||
|
||||
test("ignores anonymous operations", () => {
|
||||
expect(getGraphQLOperationNames(`{ user { id } }`)).toEqual([]);
|
||||
});
|
||||
|
||||
test("returns unique operation names in document order", () => {
|
||||
expect(
|
||||
getGraphQLOperationNames(`
|
||||
query GetUser { user { id } }
|
||||
query GetUser { user { name } }
|
||||
query ListUsers { users { id } }
|
||||
`),
|
||||
).toEqual(["GetUser", "ListUsers"]);
|
||||
});
|
||||
|
||||
test("returns no operations for invalid in-progress documents", () => {
|
||||
expect(getGraphQLOperationNames(`query GetUser { user {`)).toEqual([]);
|
||||
});
|
||||
|
||||
test("returns null when parsing invalid in-progress documents", () => {
|
||||
expect(parseGraphQLOperationNames(`query GetUser { user {`)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Kind, parse } from "graphql";
|
||||
|
||||
export function getGraphQLOperationNames(query: string): string[] {
|
||||
return parseGraphQLOperationNames(query) ?? [];
|
||||
}
|
||||
|
||||
export function parseGraphQLOperationNames(query: string): string[] | null {
|
||||
try {
|
||||
const names: string[] = [];
|
||||
|
||||
for (const definition of parse(query).definitions) {
|
||||
if (definition.kind !== Kind.OPERATION_DEFINITION || definition.name == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = definition.name.value;
|
||||
if (!names.includes(name)) {
|
||||
names.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
return names;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import {
|
||||
BODY_TYPE_BINARY,
|
||||
BODY_TYPE_FORM_URLENCODED,
|
||||
BODY_TYPE_GRAPHQL,
|
||||
BODY_TYPE_JSON,
|
||||
BODY_TYPE_NONE,
|
||||
BODY_TYPE_OTHER,
|
||||
BODY_TYPE_XML,
|
||||
} from "./model_util";
|
||||
import { convertRequestBody } from "./requestBodyConversion";
|
||||
|
||||
describe("convertRequestBody", () => {
|
||||
test("converts imported JSON GraphQL bodies to GraphQL shape", () => {
|
||||
const body = convertRequestBody({
|
||||
fromBodyType: BODY_TYPE_JSON,
|
||||
toBodyType: BODY_TYPE_GRAPHQL,
|
||||
body: {
|
||||
text: JSON.stringify({
|
||||
query: "query GetUser($id: ID!) { user(id: $id) { name } }",
|
||||
variables: { id: "123" },
|
||||
operationName: "GetUser",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
expect(body).toEqual({
|
||||
query: "query GetUser($id: ID!) { user(id: $id) { name } }",
|
||||
variables: '{\n "id": "123"\n}',
|
||||
operationName: "GetUser",
|
||||
});
|
||||
});
|
||||
|
||||
test("converts GraphQL bodies to JSON text", () => {
|
||||
const body = convertRequestBody({
|
||||
fromBodyType: BODY_TYPE_GRAPHQL,
|
||||
toBodyType: BODY_TYPE_JSON,
|
||||
body: {
|
||||
query: "query GetUser($id: ID!) { user(id: $id) { name } }",
|
||||
variables: '{ "id": "123" }',
|
||||
operationName: "GetUser",
|
||||
},
|
||||
});
|
||||
|
||||
expect(body).toEqual({
|
||||
text: JSON.stringify(
|
||||
{
|
||||
query: "query GetUser($id: ID!) { user(id: $id) { name } }",
|
||||
variables: { id: "123" },
|
||||
operationName: "GetUser",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
test("converts urlencoded forms to urlencoded text for text-like bodies", () => {
|
||||
const body = convertRequestBody({
|
||||
fromBodyType: BODY_TYPE_FORM_URLENCODED,
|
||||
toBodyType: BODY_TYPE_OTHER,
|
||||
body: {
|
||||
form: [
|
||||
{ enabled: true, name: "basic", value: "aaa" },
|
||||
{ enabled: true, name: "funky stuff", value: "*)%&#$)@ *$#)@&" },
|
||||
{ enabled: false, name: "disabled", value: "hidden" },
|
||||
{ enabled: true, name: "", value: "unnamed" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(body).toEqual({
|
||||
text: "basic=aaa&funky+stuff=*%29%25%26%23%24%29%40+*%24%23%29%40%26",
|
||||
});
|
||||
});
|
||||
|
||||
test("converts urlencoded forms to JSON text for JSON bodies", () => {
|
||||
const body = convertRequestBody({
|
||||
fromBodyType: BODY_TYPE_FORM_URLENCODED,
|
||||
toBodyType: BODY_TYPE_JSON,
|
||||
body: {
|
||||
form: [
|
||||
{ enabled: true, name: "tag", value: "one" },
|
||||
{ enabled: true, name: "tag", value: "two" },
|
||||
{ enabled: true, name: "limit", value: "10" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(body).toEqual({
|
||||
text: JSON.stringify({ tag: ["one", "two"], limit: "10" }, null, 2),
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves text when converting to form bodies cannot build form pairs", () => {
|
||||
const body = convertRequestBody({
|
||||
fromBodyType: BODY_TYPE_XML,
|
||||
toBodyType: BODY_TYPE_FORM_URLENCODED,
|
||||
body: { text: "a=1&b=two+words" },
|
||||
});
|
||||
|
||||
expect(body).toEqual({
|
||||
text: "a=1&b=two+words",
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves JSON text that is not a GraphQL envelope", () => {
|
||||
const body = convertRequestBody({
|
||||
fromBodyType: BODY_TYPE_JSON,
|
||||
toBodyType: BODY_TYPE_GRAPHQL,
|
||||
body: { text: JSON.stringify({ name: "Yaak" }) },
|
||||
});
|
||||
|
||||
expect(body).toEqual({
|
||||
text: JSON.stringify({ name: "Yaak" }),
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves JSON arrays and primitives when converting to GraphQL", () => {
|
||||
for (const text of [JSON.stringify([1, 2, 3]), JSON.stringify("query"), "123", "null"]) {
|
||||
const body = convertRequestBody({
|
||||
fromBodyType: BODY_TYPE_JSON,
|
||||
toBodyType: BODY_TYPE_GRAPHQL,
|
||||
body: { text },
|
||||
});
|
||||
|
||||
expect(body).toEqual({ text });
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves text when converting to binary cannot build a file body", () => {
|
||||
const body = convertRequestBody({
|
||||
fromBodyType: BODY_TYPE_JSON,
|
||||
toBodyType: BODY_TYPE_BINARY,
|
||||
body: { text: '{ "name": "Yaak" }' },
|
||||
});
|
||||
|
||||
expect(body).toEqual({
|
||||
text: '{ "name": "Yaak" }',
|
||||
});
|
||||
});
|
||||
|
||||
test("clears body when converting to no body", () => {
|
||||
const body = convertRequestBody({
|
||||
fromBodyType: BODY_TYPE_JSON,
|
||||
toBodyType: BODY_TYPE_NONE,
|
||||
body: { text: '{ "name": "Yaak" }' },
|
||||
});
|
||||
|
||||
expect(body).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import type { HttpRequest } from "@yaakapp-internal/models";
|
||||
import {
|
||||
BODY_TYPE_BINARY,
|
||||
BODY_TYPE_FORM_MULTIPART,
|
||||
BODY_TYPE_FORM_URLENCODED,
|
||||
BODY_TYPE_GRAPHQL,
|
||||
BODY_TYPE_JSON,
|
||||
BODY_TYPE_NONE,
|
||||
} from "./model_util";
|
||||
|
||||
type Body = HttpRequest["body"];
|
||||
type BodyType = HttpRequest["bodyType"];
|
||||
type GraphQLBody = {
|
||||
query: string;
|
||||
variables: string | undefined;
|
||||
operationName?: string;
|
||||
};
|
||||
|
||||
export function convertRequestBody({
|
||||
body,
|
||||
fromBodyType,
|
||||
toBodyType,
|
||||
}: {
|
||||
body: Body;
|
||||
fromBodyType: BodyType;
|
||||
toBodyType: BodyType;
|
||||
}): Body {
|
||||
if (toBodyType === BODY_TYPE_NONE) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (toBodyType === BODY_TYPE_GRAPHQL) {
|
||||
return toGraphQLBody(body) ?? body;
|
||||
}
|
||||
|
||||
if (toBodyType === BODY_TYPE_FORM_URLENCODED || toBodyType === BODY_TYPE_FORM_MULTIPART) {
|
||||
return toFormBody(body) ?? body;
|
||||
}
|
||||
|
||||
if (toBodyType === BODY_TYPE_BINARY) {
|
||||
return typeof body.filePath === "string" ? { filePath: body.filePath } : body;
|
||||
}
|
||||
|
||||
return toTextBody(body, fromBodyType, toBodyType) ?? body;
|
||||
}
|
||||
|
||||
export function normalizeGraphQLBody(body: Body): GraphQLBody {
|
||||
return toGraphQLBody(body) ?? { query: "", variables: undefined };
|
||||
}
|
||||
|
||||
function toGraphQLBody(body: Body): GraphQLBody | null {
|
||||
if (typeof body.query === "string") {
|
||||
const result: GraphQLBody = {
|
||||
query: body.query,
|
||||
variables: typeof body.variables === "string" ? body.variables : undefined,
|
||||
};
|
||||
if (typeof body.operationName === "string") {
|
||||
result.operationName = body.operationName;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
if (typeof body.text === "string") {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(body.text);
|
||||
if (!isRecord(parsed)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof parsed.query !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const query = parsed.query;
|
||||
const variables =
|
||||
parsed.variables == null ? undefined : JSON.stringify(parsed.variables, null, 2);
|
||||
|
||||
const result: GraphQLBody = { query, variables };
|
||||
if (typeof parsed.operationName === "string") {
|
||||
result.operationName = parsed.operationName;
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch {
|
||||
return { query: body.text, variables: undefined };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function toFormBody(body: Body): Body | null {
|
||||
if (Array.isArray(body.form)) {
|
||||
return {
|
||||
form: body.form.map((p) => ({
|
||||
enabled: p.enabled !== false,
|
||||
name: typeof p.name === "string" ? p.name : "",
|
||||
value: stringifyFormValue(p.value ?? p.file),
|
||||
contentType: typeof p.contentType === "string" ? p.contentType : undefined,
|
||||
filename: typeof p.filename === "string" ? p.filename : undefined,
|
||||
file: typeof p.file === "string" ? p.file : undefined,
|
||||
id: typeof p.id === "string" ? p.id : undefined,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function toTextBody(body: Body, fromBodyType: BodyType, toBodyType: BodyType): Body | null {
|
||||
const sendJsonComments =
|
||||
typeof body.sendJsonComments === "boolean" ? { sendJsonComments: body.sendJsonComments } : {};
|
||||
|
||||
if (typeof body.text === "string") {
|
||||
return { text: body.text, ...sendJsonComments };
|
||||
}
|
||||
|
||||
if (Array.isArray(body.form)) {
|
||||
if (toBodyType === BODY_TYPE_JSON) {
|
||||
return { text: JSON.stringify(formBodyToObject(body.form), null, 2) };
|
||||
}
|
||||
|
||||
return { text: formBodyToUrlEncodedText(body.form) };
|
||||
}
|
||||
|
||||
if (typeof body.query === "string") {
|
||||
if (toBodyType === BODY_TYPE_JSON || fromBodyType === BODY_TYPE_GRAPHQL) {
|
||||
const value: Record<string, unknown> = { query: body.query };
|
||||
if (typeof body.variables === "string" && body.variables.trim() !== "") {
|
||||
value.variables = parseJson(body.variables) ?? body.variables;
|
||||
}
|
||||
if (typeof body.operationName === "string" && body.operationName.trim() !== "") {
|
||||
value.operationName = body.operationName;
|
||||
}
|
||||
|
||||
return { text: JSON.stringify(value, null, 2) };
|
||||
}
|
||||
|
||||
return { text: body.query };
|
||||
}
|
||||
|
||||
if (typeof body.filePath === "string") {
|
||||
return { text: body.filePath };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function formBodyToUrlEncodedText(form: unknown[]): string {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
for (const pair of form) {
|
||||
if (!isRecord(pair)) continue;
|
||||
if (pair.enabled === false) continue;
|
||||
if (typeof pair.name !== "string" || pair.name === "") continue;
|
||||
params.append(pair.name, stringifyFormValue(pair.value));
|
||||
}
|
||||
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
function formBodyToObject(form: unknown[]) {
|
||||
const result: Record<string, unknown> = {};
|
||||
|
||||
for (const pair of form) {
|
||||
if (!isRecord(pair)) continue;
|
||||
if (pair.enabled === false) continue;
|
||||
if (typeof pair.name !== "string" || pair.name === "") continue;
|
||||
|
||||
const value = stringifyFormValue(pair.value);
|
||||
if (pair.name in result) {
|
||||
const existing = result[pair.name];
|
||||
result[pair.name] = Array.isArray(existing) ? [...existing, value] : [existing, value];
|
||||
} else {
|
||||
result[pair.name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function stringifyFormValue(value: unknown): string {
|
||||
if (value == null) return "";
|
||||
if (typeof value === "string") return value;
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function parseJson(text: string): unknown | null {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value != null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
Reference in New Issue
Block a user