@junaidatari/json2ts
Version:
Convert JSON objects to TypeScript interfaces automatically.
72 lines • 2.98 kB
JavaScript
;
/**
* @author Junaid Atari <mj.atari@gmail.com>
* @copyright 2025 Junaid Atari
* @see https://github.com/blacksmoke26
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
// utils
const ConverterUtils_1 = __importDefault(require("../utils/ConverterUtils"));
/**
* Abstract base class for JSON to TypeScript interface converters.
* Provides robust common functionality with enhanced error handling and validation.
*/
class ConverterBase {
/**
* Protected constructor to enforce factory pattern usage.
*/
constructor() {
}
/**
* Converts a JSON object into a TypeScript interface.
* Implements template method pattern with validation and error handling.
*
* @param jsonData The JSON object to convert. Must be a valid object structure.
* @param interfaceName The name for the generated interface. Defaults to 'RootObject'.
* @param exportType Determines the export strategy. Defaults to 'root'.
* @param options Configuration options for the conversion process.
* @returns Formatted TypeScript interface string or null if conversion fails.
* @throws {Error} If conversion encounters unrecoverable errors.
* @example
* ```typescript
* const json = '{"name": "John", "age": 30}';
* const interface = ConverterBase.convert(json, 'Person', 'all', {
* arrayMaxTupleSize: 5,
* strict: true
* });
* ```
*/
static convert(jsonData, interfaceName = 'RootObject', exportType = 'root', options = {}) {
// Validate interface name
if (!ConverterUtils_1.default.checkIdentifier(interfaceName)) {
throw new Error(`Invalid interface name: "${interfaceName}". Must be a valid TypeScript identifier.`);
}
// Parse JSON with enhanced error handling
const parseResult = ConverterUtils_1.default.jsonParse(jsonData);
if (parseResult.error) {
console.error(`Conversion failed: ${parseResult.error}${parseResult.details ? ` - ${parseResult.details}` : ''}`);
return null;
}
// Create converter instance and delegate conversion
try {
const converter = this.createConverter(options);
return converter.convertJson(parseResult.data, interfaceName, exportType);
}
catch (error) {
console.error('Conversion failed:', error instanceof Error ? error.message : String(error));
return null;
}
}
/**
* Factory method to create converter instance.
* Must be implemented by concrete converter classes.
*/
static createConverter(options) {
throw new Error('createConverter must be implemented by concrete converter class');
}
}
exports.default = ConverterBase;
//# sourceMappingURL=ConverterBase.js.map