UNPKG

@scalar/api-reference

Version:

Generate beautiful API references from OpenAPI documents

61 lines (60 loc) 1.91 kB
import { getResolvedRef } from "@scalar/workspace-store/helpers/get-resolved-ref"; import { isArraySchema } from "@scalar/workspace-store/schemas/v3.1/strict/type-guards"; import { getRefName } from "./get-ref-name.js"; const getModelNameFromSchema = (schemaOrRef) => { if (!schemaOrRef) { return null; } if ("$ref" in schemaOrRef) { const refName = getRefName(schemaOrRef); if (refName) { return refName; } } const schema = getResolvedRef(schemaOrRef); if (schema.title) { return schema.title; } if (schema.name) { return schema.name; } return null; }; const formatTypeWithModel = (type, modelName) => `${type} ${modelName}${type === "array" ? "[]" : ""}`; const getModelName = (value, hideModelNames = false) => { if (!("type" in value) || hideModelNames) { return null; } const valueType = value.type; const modelName = getModelNameFromSchema(value); if (modelName && value.title) { return valueType === "array" ? `array ${modelName}[]` : modelName; } if (isArraySchema(value) && value.items) { const items = getResolvedRef(value.items); const itemName = items.title; if (itemName) { return formatTypeWithModel(valueType, itemName); } const itemModelName = getModelNameFromSchema(value.items); if (itemModelName && "type" in items && itemModelName !== items.type) { return formatTypeWithModel(valueType, itemModelName); } if ("type" in items) { return formatTypeWithModel(valueType, Array.isArray(items.type) ? items.type.join(" | ") : items.type); } return formatTypeWithModel(valueType, "object"); } if (modelName && modelName !== valueType) { if (modelName.startsWith("Array of ")) { const itemType = modelName.slice(9); return `array ${itemType}[]`; } return modelName; } return null; }; export { getModelName, getModelNameFromSchema };