UNPKG

@apistudio/apim-cli

Version:

CLI for API Management Products

52 lines (51 loc) 1.93 kB
import fs from 'fs'; import path from 'path'; import yaml from 'js-yaml'; export async function generateTypes({ specPath, outputRoot }) { const content = fs.readFileSync(specPath, 'utf8'); const spec = yaml.load(content); const components = spec.components?.schemas; if (!components) { throw new Error("No components.schemas found in OpenAPI spec."); } for (const [name, schema] of Object.entries(components)) { const category = getCategory(name.toLowerCase()); const outDir = path.join(outputRoot, 'generated/source/assets/', category); fs.mkdirSync(outDir, { recursive: true }); const interfaceStr = generateInterface(name, schema); const filePath = path.join(outDir, '/', `${name}.ts`); fs.writeFileSync(filePath, interfaceStr, 'utf8'); console.log(`Generated: ${filePath}`); } } function getCategory(name) { return ['api', 'product', 'plan'].includes(name) ? 'common' : 'policies'; } function generateInterface(name, schema) { const lines = []; lines.push(`/**`); lines.push(` * Copyright IBM Corp. 2024, 2025`); lines.push(` */\n`); if (schema.description) { lines.push(`/** ${schema.description} */`); } lines.push(`export interface ${name} {`); if (schema.properties) { for (const [propName, prop] of Object.entries(schema.properties)) { const type = resolveType(prop); const optional = !schema.required?.includes(propName) ? '?' : ''; lines.push(` ${propName}${optional}: ${type};`); } } lines.push(`}`); return lines.join('\n'); } function resolveType(prop) { if (prop.enum) return prop.enum.map((v) => `"${v}"`).join(' | '); if (prop.type === 'array') return `${resolveType(prop.items)}[]`; if (prop.type === 'object') return `{ [key: string]: any }`; return prop.type || 'any'; }