Skip to content

Commit 373183a

Browse files
authored
Safe parse OpenAPI JSON schema (#3046)
1 parent e9fa50d commit 373183a

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

.changeset/little-wombats-visit.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@gitbook/react-openapi': patch
3+
---
4+
5+
Safe parse OpenAPI JSON schema

packages/react-openapi/src/OpenAPISchema.tsx

+18-7
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ export function OpenAPISchemaPropertiesFromServer(props: {
122122
return (
123123
<OpenAPISchemaProperties
124124
id={props.id}
125-
properties={JSON.parse(props.properties, retrocycle())}
125+
properties={safeJSONParse(props.properties)}
126126
context={props.context}
127127
/>
128128
);
@@ -172,12 +172,7 @@ export function OpenAPIRootSchemaFromServer(props: {
172172
schema: string;
173173
context: OpenAPIClientContext;
174174
}) {
175-
return (
176-
<OpenAPIRootSchema
177-
schema={JSON.parse(props.schema, retrocycle())}
178-
context={props.context}
179-
/>
180-
);
175+
return <OpenAPIRootSchema schema={safeJSONParse(props.schema)} context={props.context} />;
181176
}
182177

183178
/**
@@ -465,3 +460,19 @@ function getDisclosureLabel(schema: OpenAPIV3.SchemaObject): string {
465460

466461
return schema.title || 'child attributes';
467462
}
463+
464+
/**
465+
* Safely parse a JSON string using retrocycle.
466+
* If parsing fails, it falls back to standard JSON.parse.
467+
*/
468+
function safeJSONParse(jsonString: string) {
469+
try {
470+
return JSON.parse(jsonString, retrocycle());
471+
} catch {
472+
try {
473+
return JSON.parse(jsonString);
474+
} catch (fallbackError) {
475+
throw new Error(`Failed to parse JSON string: ${fallbackError}`);
476+
}
477+
}
478+
}

0 commit comments

Comments
 (0)