UNPKG

next-dev

Version:

Tentu, berikut adalah markdown yang telah diperbaiki:

146 lines (145 loc) 5.73 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const path_1 = __importDefault(require("path")); const fs_1 = __importDefault(require("fs")); const prettier_1 = __importDefault(require("prettier")); const axios_1 = __importDefault(require("axios")); const cli_progress_1 = require("cli-progress"); function jsonToTypeScript(json, interfaceName = 'RootObject') { const getType = (value) => { if (Array.isArray(value)) { if (value.length > 0) { const arrayType = getType(value[0]); return `${arrayType}[]`; } else { return 'any[]'; } } else if (typeof value === 'object' && value !== null) { return `{ ${Object.entries(value).map(([k, v]) => `${k}: ${getType(v)}`).join('; ')} }`; } else if (typeof value === 'string') { return 'string'; } else if (typeof value === 'number') { return 'number'; } else if (typeof value === 'boolean') { return 'boolean'; } else { return 'any'; } }; const buildInterface = (name, obj) => { const entries = Object.entries(obj).map(([key, value]) => { const type = getType(value); return `${key}: ${type};`; }).join('\n '); return `export interface ${name} {\n ${entries}\n}`; }; const interfaces = []; const processObject = (obj, name) => { const interfaceString = buildInterface(name, obj); interfaces.push(interfaceString); for (const [key, value] of Object.entries(obj)) { if (typeof value === 'object' && value !== null && !Array.isArray(value)) { processObject(value, capitalizeFirstLetter(key)); } } }; const capitalizeFirstLetter = (str) => { return str.charAt(0).toUpperCase() + str.slice(1); }; processObject(json, interfaceName); return interfaces.reverse().join('\n\n'); } async function fetchJsonFromUrl(url) { const response = await axios_1.default.get(url); return response.data; } function readJsonFromFile(filePath) { const fileContent = fs_1.default.readFileSync(filePath, 'utf-8'); try { return JSON.parse(fileContent); } catch (error) { throw new Error(`Error parsing JSON from file ${filePath}: ${error.message}`); } } async function readJsonFromDir(dirPath) { const files = fs_1.default.readdirSync(dirPath).filter(file => file.endsWith('.json')); const jsonObjects = files.map(file => { const filePath = path_1.default.join(dirPath, file); return { name: path_1.default.basename(file, '.json'), json: readJsonFromFile(filePath) }; }); return jsonObjects; } async function processAndSaveJson(json, name, outputDir, log) { try { if (typeof json === 'string') { log && console.log('Converting JSON string to object...'); json = JSON.parse(json); } } catch (error) { throw new Error(`Invalid JSON string provided: ${error.message}`); } if (Array.isArray(json)) { if (json.length === 0) { throw new Error("The JSON array is empty."); } json = json[0]; // Use the first element of the array for generating the interface } const tsInterfaces = jsonToTypeScript(json, name); const prettyTsInterfaces = await prettier_1.default.format(tsInterfaces, { parser: "typescript" }); const outputFile = path_1.default.join(outputDir, `${name}.ts`); log && console.log(`Writing ${outputFile}`); fs_1.default.writeFileSync(outputFile, prettyTsInterfaces, 'utf8'); console.log(`✨✨✨ file://${outputFile} DONE ✨✨✨`); } async function genModel(argv) { const { log, out, name, url, file, dir } = argv; if (!url && !file && !dir) { throw new Error("You must provide one of the following: url, file, or dir"); } const outputDir = path_1.default.resolve(process.cwd(), out); if (!fs_1.default.existsSync(outputDir)) { log && console.log(`Creating output directory: ${outputDir}`); fs_1.default.mkdirSync(outputDir, { recursive: true }); } try { if (url) { log && console.log(`Fetching JSON from URL: ${url}`); const json = await fetchJsonFromUrl(url); await processAndSaveJson(json, name, outputDir, log); } else if (file) { log && console.log(`Reading JSON from file: ${file}`); const json = readJsonFromFile(file); const outputName = path_1.default.basename(file, '.json'); await processAndSaveJson(json, outputName, outputDir, log); } else if (dir) { log && console.log(`Reading JSON from directory: ${dir}`); const jsonObjects = await readJsonFromDir(dir); // Initialize progress bar const progressBar = new cli_progress_1.SingleBar({}, cli_progress_1.Presets.shades_classic); progressBar.start(jsonObjects.length, 0); for (let index = 0; index < jsonObjects.length; index++) { const { name, json } = jsonObjects[index]; await processAndSaveJson(json, name, outputDir, log); progressBar.update(index + 1); } progressBar.stop(); } } catch (error) { console.error(`Error processing JSON: ${error.message}`); } } exports.default = genModel;