UNPKG

@scalar/api-reference

Version:

Generate beautiful API references from OpenAPI documents

69 lines (68 loc) 2.37 kB
import { compositions } from "./schema-composition.js"; import { resolve } from "@scalar/workspace-store/resolve"; //#region src/components/Content/Schema/helpers/optimize-value-for-display.ts /** * Optimize the value by removing nulls from compositions and merging root properties. * * TODO: figure out what this does */ 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 = resolve.schema(_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; } if ((composition === "oneOf" || composition === "anyOf") && (hasRootProperties || filteredSchemas.some((schema) => schema.allOf))) { const mergedSchemas = filteredSchemas.map((_schema) => { const schema = resolve.schema(_schema); if (schema.allOf?.length === 1) { const { allOf, ...otherProps } = schema; return { ...rootProperties, ...otherProps, ...resolve.schema(allOf[0]) }; } return { ...rootProperties, ...schema }; }); const result = { [composition]: mergedSchemas }; if (typeof value.description === "string") result.description = value.description; 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 }; } //#endregion export { optimizeValueForDisplay }; //# sourceMappingURL=optimize-value-for-display.js.map