|
| 1 | +const { program } = require('commander'); |
| 2 | +const { exec } = require('child_process'); |
| 3 | +const { renameSync, rmdirSync, unlinkSync } = require('fs'); |
| 4 | +const { dirname, basename, join } = require('path'); |
| 5 | + |
| 6 | +program |
| 7 | + .option('-i, --input <input>', 'Input YAML schema file path') |
| 8 | + .option('-o, --output <output>', 'Output path including the filename (e.g., /output/api.js)') |
| 9 | + .parse(process.argv); |
| 10 | + |
| 11 | +// Function to run a command and handle success or failure |
| 12 | +function runCommand(command, successMessage, failureMessage) { |
| 13 | + return new Promise((resolve, reject) => { |
| 14 | + exec(command, (error, stdout, stderr) => { |
| 15 | + if (error) { |
| 16 | + console.error(failureMessage); |
| 17 | + console.error(stderr); |
| 18 | + reject(error); |
| 19 | + } else { |
| 20 | + console.log(successMessage); |
| 21 | + resolve(); |
| 22 | + } |
| 23 | + }); |
| 24 | + }); |
| 25 | +} |
| 26 | + |
| 27 | +async function generateAPI(inputFilePath, outputFilePath) { |
| 28 | + try { |
| 29 | + // Convert YAML schema to JSON schema |
| 30 | + const yamlToJSONCommand = `redocly bundle ${inputFilePath} -o ./openapi.json --ext json`; |
| 31 | + await runCommand(yamlToJSONCommand, 'JSON bundle generation successful', 'JSON bundle generation failed'); |
| 32 | + |
| 33 | + // Run OpenAPI generator |
| 34 | + const openApiGeneratorCommand = 'npx @rtk-query/codegen-openapi openapi-config.ts'; |
| 35 | + await runCommand(openApiGeneratorCommand, 'OpenAPI generation successful', 'OpenAPI generation failed'); |
| 36 | + |
| 37 | + // Run TypeScript compilation |
| 38 | + const tscCommand = 'tsc --build tsconfig.json'; |
| 39 | + await runCommand(tscCommand, 'TypeScript compilation successful', 'TypeScript compilation failed'); |
| 40 | + |
| 41 | + // Move api.js from the generated folder to the output path |
| 42 | + console.log('Removing Build Artifacts'); |
| 43 | + const outputPath = dirname(outputFilePath); |
| 44 | + const outputFilename = basename(outputFilePath); |
| 45 | + renameSync('./dist/api.js', join(outputPath, outputFilename)); |
| 46 | + rmdirSync('./dist', { recursive: true }); |
| 47 | + unlinkSync('./openapi.json'); |
| 48 | + unlinkSync('./api.ts'); |
| 49 | + |
| 50 | + console.log('API generation successful'); |
| 51 | + process.exit(0); |
| 52 | + } catch (error) { |
| 53 | + console.error('API generation failed'); |
| 54 | + process.exit(1); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +const { input, output } = program.opts(); |
| 59 | + |
| 60 | +if (!input || !output) { |
| 61 | + console.error('Please provide both input and output options.'); |
| 62 | + process.exit(1); |
| 63 | +} |
| 64 | + |
| 65 | +generateAPI(input, output); |
0 commit comments