UNPKG

@scalar/api-reference

Version:

Generate beautiful API references from OpenAPI documents

65 lines (64 loc) 2.23 kB
import { getResolvedRef } from "@scalar/workspace-store/helpers/get-resolved-ref"; import { compositions } from "./schema-composition.js"; function optimizeValueForDisplay(value) { if (!value || typeof value !== "object") { return value; } const composition = compositions.find((keyword) => keyword in value && keyword !== "not"); if (!composition) { return { ...value }; } const schemas = value[composition]; if (!Array.isArray(schemas)) { return { ...value }; } const { [composition]: _, nullable: originalNullable, ...rootProperties } = value; const hasRootProperties = Object.keys(rootProperties).length > 0; const { filteredSchemas, hasNullSchema } = schemas.reduce( (acc, _schema) => { const schema = getResolvedRef(_schema); if ("type" in schema && schema.type === "null") { acc.hasNullSchema = true; } else { acc.filteredSchemas.push(schema); } return acc; }, { filteredSchemas: [], hasNullSchema: false } ); const shouldBeNullable = hasNullSchema || originalNullable === true; if (filteredSchemas.length === 1) { const mergedSchema = { ...rootProperties, ...filteredSchemas[0] }; if (shouldBeNullable) { mergedSchema.nullable = true; } return mergedSchema; } const shouldMergeRootProperties = (composition === "oneOf" || composition === "anyOf") && (hasRootProperties || filteredSchemas.some((schema) => schema.allOf)); if (shouldMergeRootProperties) { const mergedSchemas = filteredSchemas.map((_schema) => { const schema = getResolvedRef(_schema); if (schema.allOf?.length === 1) { const { allOf, ...otherProps } = schema; return { ...rootProperties, ...otherProps, ...getResolvedRef(allOf[0]) }; } return { ...rootProperties, ...schema }; }); const result = { [composition]: mergedSchemas }; if (shouldBeNullable) { result.nullable = true; } return result; } if (filteredSchemas.length !== schemas.length) { const result = { ...value, [composition]: filteredSchemas }; if (shouldBeNullable) { result.nullable = true; } return result; } return { ...value }; } export { optimizeValueForDisplay };