Skip to content

Missing top-level required OpenAPI alternatives #3207

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/shy-plums-deny.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---

Missing top-level required OpenAPI alternatives
38 changes: 36 additions & 2 deletions packages/react-openapi/src/OpenAPISchema.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,9 @@ function flattenAlternatives(
schemasOrRefs: (OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject)[],
ancestors: Set<OpenAPIV3.SchemaObject>
): OpenAPIV3.SchemaObject[] {
// Get the parent schema's required fields from the most recent ancestor
const latestAncestor = Array.from(ancestors).pop();

return schemasOrRefs.reduce<OpenAPIV3.SchemaObject[]>((acc, schemaOrRef) => {
if (checkIsReference(schemaOrRef)) {
return acc;
Expand All @@ -580,16 +583,47 @@ function flattenAlternatives(
if (schemaOrRef[alternativeType] && !ancestors.has(schemaOrRef)) {
const schemas = getSchemaAlternatives(schemaOrRef, ancestors);
if (schemas) {
acc.push(...schemas);
acc.push(
...schemas.map((schema) => ({
...schema,
required: mergeRequiredFields(schema, latestAncestor),
}))
);
}
return acc;
}

acc.push(schemaOrRef);
// For direct schemas, handle required fields
const schema = {
...schemaOrRef,
required: mergeRequiredFields(schemaOrRef, latestAncestor),
};

acc.push(schema);
return acc;
}, []);
}

/**
* Merge the required fields of a schema with the required fields of its latest ancestor.
*/
function mergeRequiredFields(
schemaOrRef: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject,
latestAncestor: OpenAPIV3.SchemaObject | undefined
) {
if (!schemaOrRef.required && !latestAncestor?.required) {
return undefined;
}

if (checkIsReference(schemaOrRef)) {
return latestAncestor?.required;
}

return Array.from(
new Set([...(latestAncestor?.required || []), ...(schemaOrRef.required || [])])
);
}

function getSchemaTitle(schema: OpenAPIV3.SchemaObject): string {
// Otherwise try to infer a nice title
let type = 'any';
Expand Down