UNPKG

@apistudio/apim-cli

Version:

CLI for API Management Products

84 lines (63 loc) 2.9 kB
import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import yaml from 'js-yaml'; // Get the directory name in ESM const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Path to the YAML file const yamlFilePath = path.resolve(__dirname, '../../schema_specification/V12_openAPI_specification_smith_wmgw.yaml'); // Path for the output JSON file const outputFilePath = path.resolve(__dirname, './combined-source.json'); // Main function to generate the combined JSON async function generateCombinedJson() { try { console.log(`Reading YAML file from: ${yamlFilePath}`); // Read the YAML file const yamlContent = fs.readFileSync(yamlFilePath, 'utf8'); // Parse the YAML content const parsedYaml = yaml.load(yamlContent); // Check if components and schemas exist if (!parsedYaml.components || !parsedYaml.components.schemas) { throw new Error('YAML file does not contain components.schemas section'); } const schemas = parsedYaml.components.schemas; // Create the result object const result = {}; // Process each schema for (const [schemaName, schemaContent] of Object.entries(schemas)) { // Skip the AssetDiscriminator and KindEnums schemas as they are special cases if (schemaName === 'AssetDiscriminator' || schemaName === 'KindEnums') { // Still include them with their special names result[`api.ibm.com-v1_${schemaName.toLowerCase()}.json`] = schemaContent; continue; } // For regular schemas, get the apiVersion and kind let apiVersion = 'api.ibm.com/v1'; // Default apiVersion let kind = schemaName; // If the schema has apiVersion and kind properties, use those if (schemaContent.properties) { if (schemaContent.properties.apiVersion && schemaContent.properties.apiVersion.default) { apiVersion = schemaContent.properties.apiVersion.default; } if (schemaContent.properties.kind && schemaContent.properties.kind.enum) { kind = schemaContent.properties.kind.enum[0]; } } // Replace / with _ in apiVersion const formattedApiVersion = apiVersion.replace(/\//g, '_'); // Create the key in the format apiVersion_kind.json const key = `${formattedApiVersion}_${kind.toLowerCase()}.json`; // Add to result object result[key] = schemaContent; } // Write the combined JSON to a file fs.writeFileSync(outputFilePath, JSON.stringify(result, null, 2)); console.log(`Successfully generated combined-source.json with ${Object.keys(result).length} schemas`); } catch (error) { console.error('Error generating combined JSON:', error); } } // Run the main function generateCombinedJson(); // Made with Bob