Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: support json in resource body (#2953)

Bogdan Chadkin8053be7bb708
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
index f9f04a6399..f393865e9d 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -47,6 +47,7 @@ import {
useField,
composeFields,
} from "~/shared/form-utils";
+import { ExpressionEditor } from "~/builder/shared/expression-editor";
const validateHeaderName = (value: string) =>
value.trim().length === 0 ? "Header name is required" : undefined;
@@ -125,22 +126,6 @@ const HeaderPair = ({
</Label>
<Box css={{ gridArea: "value-input", position: "relative" }}>
<BindingControl>
- <BindingPopover
- scope={editorScope}
- aliases={editorAliases}
- variant={isLiteralExpression(value) ? "default" : "bound"}
- value={value}
- onChange={(newValue) => {
- valueField.onChange(newValue);
- valueField.onBlur();
- onChange(name, newValue);
- }}
- onRemove={(evaluatedValue) => {
- valueField.onChange(JSON.stringify(evaluatedValue));
- valueField.onBlur();
- onChange(name, JSON.stringify(evaluatedValue));
- }}
- />
<InputErrorsTooltip
errors={valueField.error ? [valueField.error] : undefined}
>
@@ -158,6 +143,22 @@ const HeaderPair = ({
onBlur={valueField.onBlur}
/>
</InputErrorsTooltip>
+ <BindingPopover
+ scope={editorScope}
+ aliases={editorAliases}
+ variant={isLiteralExpression(value) ? "default" : "bound"}
+ value={value}
+ onChange={(newValue) => {
+ valueField.onChange(newValue);
+ valueField.onBlur();
+ onChange(name, newValue);
+ }}
+ onRemove={(evaluatedValue) => {
+ valueField.onChange(JSON.stringify(evaluatedValue));
+ valueField.onBlur();
+ onChange(name, JSON.stringify(evaluatedValue));
+ }}
+ />
</BindingControl>
</Box>
@@ -311,6 +312,98 @@ const $selectedInstanceScope = computed(
}
);
+const BodyField = ({
+ editorAliases,
+ editorScope,
+ contentType,
+ bodyField,
+}: {
+ editorAliases: Map<string, string>;
+ editorScope: Record<string, unknown>;
+ contentType?: string;
+ bodyField: Field<undefined | string>;
+}) => {
+ const evaluatedBodyValue =
+ bodyField.value === undefined
+ ? undefined
+ : evaluateExpressionWithinScope(bodyField.value, editorScope);
+ const evaluatedContentType = contentType
+ ? evaluateExpressionWithinScope(contentType, editorScope)
+ : undefined;
+ const isBound =
+ bodyField.value !== undefined &&
+ isLiteralExpression(bodyField.value) === false;
+ const isJsonBody = String(evaluatedContentType ?? "") === "application/json";
+
+ const [localValue, setLocalValue] = useState<undefined | string>();
+
+ return (
+ <Flex direction="column" css={{ gap: theme.spacing[3] }}>
+ <Label>Body</Label>
+ <BindingControl>
+ <InputErrorsTooltip
+ errors={bodyField.error ? [bodyField.error] : undefined}
+ >
+ {isJsonBody ? (
+ // wrap with div to position error tooltip
+ <div>
+ <ExpressionEditor
+ color={bodyField.error ? "error" : undefined}
+ // expressions with variables cannot be edited
+ readOnly={
+ localValue === undefined && isBound && bodyField.valid
+ }
+ value={
+ localValue ??
+ JSON.stringify(evaluatedBodyValue, null, 2) ??
+ bodyField.value ??
+ ""
+ }
+ onChange={(value) => {
+ setLocalValue(value);
+ bodyField.onChange(value);
+ }}
+ onBlur={() => {
+ setLocalValue(undefined);
+ bodyField.onBlur();
+ }}
+ />
+ </div>
+ ) : (
+ <TextArea
+ autoGrow={true}
+ maxRows={10}
+ // expressions with variables cannot be edited
+ disabled={isBound}
+ state={bodyField.error ? "invalid" : undefined}
+ value={String(evaluatedBodyValue ?? "")}
+ // update text value as string literal
+ onChange={(newValue) =>
+ bodyField.onChange(JSON.stringify(newValue))
+ }
+ onBlur={bodyField.onBlur}
+ />
+ )}
+ </InputErrorsTooltip>
+ <BindingPopover
+ scope={editorScope}
+ aliases={editorAliases}
+ variant={isBound ? "bound" : "default"}
+ value={bodyField.value ?? ""}
+ onChange={(value) => {
+ bodyField.onChange(value);
+ bodyField.onBlur();
+ }}
+ onRemove={(evaluatedValue) => {
+ bodyField.onChange(JSON.stringify(evaluatedValue));
+ bodyField.onBlur();
+ }}
+ />
+ </BindingControl>
+ </Flex>
+ );
+};
+
type PanelApi = ComposedFields & {
save: () => void;
};
@@ -364,12 +457,19 @@ export const ResourceForm = forwardRef<
initialValue: resource?.headers ?? [],
validate: (_value) => undefined,
});
- const bodyField = useField<string>({
- initialValue: resource?.body ?? `""`,
+ const bodyField = useField<undefined | string>({
+ initialValue: resource?.body,
validate: (value) => {
+ // skip empty expressions
+ if (value === undefined) {
+ return;
+ }
const evaluatedValue = evaluateExpressionWithinScope(value, scope);
- if (typeof evaluatedValue !== "string") {
- return "Body expects a string";
+ const isString = typeof evaluatedValue === "string";
+ const isJson =
+ typeof evaluatedValue === "object" && evaluatedValue !== null;
+ if (isString === false && isJson === false) {
+ return "Body expects a string or json";
}
},
});
@@ -428,20 +528,6 @@ export const ResourceForm = forwardRef<
<Flex direction="column" css={{ gap: theme.spacing[3] }}>
<Label htmlFor={urlId}>URL</Label>
<BindingControl>
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={isLiteralExpression(urlField.value) ? "default" : "bound"}
- value={urlField.value}
- onChange={(value) => {
- urlField.onChange(value);
- urlField.onBlur();
- }}
- onRemove={(evaluatedValue) => {
- urlField.onChange(JSON.stringify(evaluatedValue));
- urlField.onBlur();
- }}
- />
<InputErrorsTooltip
errors={urlField.error ? [urlField.error] : undefined}
>
@@ -460,6 +546,20 @@ export const ResourceForm = forwardRef<
onBlur={urlField.onBlur}
/>
</InputErrorsTooltip>
+ <BindingPopover
+ scope={scope}
+ aliases={aliases}
+ variant={isLiteralExpression(urlField.value) ? "default" : "bound"}
+ value={urlField.value}
+ onChange={(value) => {
+ urlField.onChange(value);
+ urlField.onBlur();
+ }}
+ onRemove={(evaluatedValue) => {
+ urlField.onChange(JSON.stringify(evaluatedValue));
+ urlField.onBlur();
+ }}
+ />
</BindingControl>
</Flex>
<Flex direction="column" css={{ gap: theme.spacing[3] }}>
@@ -481,46 +581,16 @@ export const ResourceForm = forwardRef<
/>
</Flex>
{method !== "get" && (
- <Flex direction="column" css={{ gap: theme.spacing[3] }}>
- <Label>Body</Label>
- <BindingControl>
- <BindingPopover
- scope={scope}
- aliases={aliases}
- variant={
- isLiteralExpression(bodyField.value) ? "default" : "bound"
- }
- value={bodyField.value}
- onChange={(value) => {
- bodyField.onChange(value);
- bodyField.onBlur();
- }}
- onRemove={(evaluatedValue) => {
- bodyField.onChange(JSON.stringify(evaluatedValue));
- bodyField.onBlur();
- }}
- />
- <InputErrorsTooltip
- errors={bodyField.error ? [bodyField.error] : undefined}
- >
- <TextArea
- autoGrow={true}
- maxRows={10}
- // expressions with variables cannot be edited
- disabled={isLiteralExpression(bodyField.value) === false}
- state={bodyField.error ? "invalid" : undefined}
- value={String(
- evaluateExpressionWithinScope(bodyField.value, scope)
- )}
- // update text value as string literal
- onChange={(newValue) =>
- bodyField.onChange(JSON.stringify(newValue))
- }
- onBlur={bodyField.onBlur}
- />
- </InputErrorsTooltip>
- </BindingControl>
- </Flex>
+ <BodyField
+ editorScope={scope}
+ editorAliases={aliases}
+ contentType={
+ headersField.value.find(
+ (header) => header.name.toLowerCase() === "content-type"
+ )?.value
+ }
+ bodyField={bodyField}
+ />
)}
</>
);
diff --git a/apps/builder/app/routes/rest.resources-loader.ts b/apps/builder/app/routes/rest.resources-loader.ts
index 61590b7f38..9d973d991a 100644
--- a/apps/builder/app/routes/rest.resources-loader.ts
+++ b/apps/builder/app/routes/rest.resources-loader.ts
@@ -1,11 +1,13 @@
import { z } from "zod";
import type { ActionArgs } from "@remix-run/node";
-import { loadResource, Resource } from "@webstudio-is/sdk";
+import { loadResource, ResourceRequest } from "@webstudio-is/sdk";
export const action = async ({ request }: ActionArgs) => {
- const computedResources = z.array(Resource).parse(await request.json());
+ const computedResources = z
+ .array(ResourceRequest)
+ .parse(await request.json());
const responses = await Promise.all(computedResources.map(loadResource));
- const output: [Resource["id"], unknown][] = [];
+ const output: [ResourceRequest["id"], unknown][] = [];
responses.forEach((response, index) => {
const request = computedResources[index];
output.push([request.id, response]);
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index 7c40da52b2..17149b6afd 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -1,5 +1,11 @@
import { atom, computed } from "nanostores";
-import type { Resource, DataSource, Instance, Prop } from "@webstudio-is/sdk";
+import type {
+ Resource,
+ DataSource,
+ Instance,
+ Prop,
+ ResourceRequest,
+} from "@webstudio-is/sdk";
import {
collectionComponent,
decodeDataSourceVariable,
@@ -433,8 +439,8 @@ const $loaderVariableValues = computed(
const computeResource = (
resource: Resource,
values: Map<DataSource["id"], unknown>
-): Resource => {
- const request: Resource = {
+): ResourceRequest => {
+ const request: ResourceRequest = {
id: resource.id,
name: resource.name,
url: computeExpression(resource.url, values),
@@ -453,7 +459,7 @@ const computeResource = (
const $computedResources = computed(
[$resources, $loaderVariableValues],
(resources, values) => {
- const computedResources: Resource[] = [];
+ const computedResources: ResourceRequest[] = [];
for (const resource of resources.values()) {
computedResources.push(computeResource(resource, values));
}
@@ -467,7 +473,7 @@ export const $areResourcesLoading = computed(
(resourcesLoadingCount) => resourcesLoadingCount > 0
);
-const loadResources = async (resourceRequests: Resource[]) => {
+const loadResources = async (resourceRequests: ResourceRequest[]) => {
$resourcesLoadingCount.set($resourcesLoadingCount.get() + 1);
const response = await fetch(restResourcesLoader(), {
method: "POST",
@@ -511,8 +517,8 @@ export const subscribeResources = () => {
(computedResources, invalidator) =>
[computedResources, invalidator] as const
).subscribe(async ([computedResources]) => {
- const matched = new Map<Resource["id"], Resource>();
- const missing = new Map<Resource["id"], Resource>();
+ const matched = new Map<Resource["id"], ResourceRequest>();
+ const missing = new Map<Resource["id"], ResourceRequest>();
for (const request of computedResources) {
const cacheKey = JSON.stringify(request);
if (cacheByKeys.has(cacheKey)) {
diff --git a/packages/sdk/src/resource-loader.ts b/packages/sdk/src/resource-loader.ts
index c9496062aa..5791fcbd30 100644
--- a/packages/sdk/src/resource-loader.ts
+++ b/packages/sdk/src/resource-loader.ts
@@ -1,6 +1,6 @@
-import type { Resource } from "./schema/resources";
+import type { ResourceRequest } from "./schema/resources";
-export const loadResource = async (resourceData: Resource) => {
+export const loadResource = async (resourceData: ResourceRequest) => {
const { url, method, headers, body } = resourceData;
const requestHeaders = new Headers(
headers.map(({ name, value }): [string, string] => [name, value])
@@ -10,7 +10,12 @@ export const loadResource = async (resourceData: Resource) => {
headers: requestHeaders,
};
if (method !== "get" && body !== undefined) {
- requestInit.body = body;
+ if (typeof body === "string") {
+ requestInit.body = body;
+ }
+ if (typeof body === "object") {
+ requestInit.body = JSON.stringify(body);
+ }
}
try {
// cloudflare workers fail when fetching url contains spaces
diff --git a/packages/sdk/src/schema/resources.ts b/packages/sdk/src/schema/resources.ts
index 0c0dc38ae9..85b2f9cbe5 100644
--- a/packages/sdk/src/schema/resources.ts
+++ b/packages/sdk/src/schema/resources.ts
@@ -28,6 +28,18 @@ export const Resource = z.object({
export type Resource = z.infer<typeof Resource>;
+// evaluated variant of resource
+export const ResourceRequest = z.object({
+ id: ResourceId,
+ name: z.string(),
+ method: Method,
+ url: z.string(),
+ headers: z.array(Header),
+ body: z.optional(z.unknown()),
+});
+
+export type ResourceRequest = z.infer<typeof ResourceRequest>;
+
export const Resources = z.map(ResourceId, Resource);
export type Resources = z.infer<typeof Resources>;