Safe parse OpenAPI JSON schema (#3046)

This commit is contained in:
Nolann B.
2025-03-26 13:55:22 +01:00
committed by GitHub
parent e9fa50dfb5
commit 373183a2cd
2 changed files with 23 additions and 7 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Safe parse OpenAPI JSON schema
+18 -7
View File
@@ -122,7 +122,7 @@ export function OpenAPISchemaPropertiesFromServer(props: {
return (
<OpenAPISchemaProperties
id={props.id}
properties={JSON.parse(props.properties, retrocycle())}
properties={safeJSONParse(props.properties)}
context={props.context}
/>
);
@@ -172,12 +172,7 @@ export function OpenAPIRootSchemaFromServer(props: {
schema: string;
context: OpenAPIClientContext;
}) {
return (
<OpenAPIRootSchema
schema={JSON.parse(props.schema, retrocycle())}
context={props.context}
/>
);
return <OpenAPIRootSchema schema={safeJSONParse(props.schema)} context={props.context} />;
}
/**
@@ -465,3 +460,19 @@ function getDisclosureLabel(schema: OpenAPIV3.SchemaObject): string {
return schema.title || 'child attributes';
}
/**
* Safely parse a JSON string using retrocycle.
* If parsing fails, it falls back to standard JSON.parse.
*/
function safeJSONParse(jsonString: string) {
try {
return JSON.parse(jsonString, retrocycle());
} catch {
try {
return JSON.parse(jsonString);
} catch (fallbackError) {
throw new Error(`Failed to parse JSON string: ${fallbackError}`);
}
}
}