@msugiura/rawsql-prisma
Version:
Prisma integration for rawsql-ts - Dynamic SQL generation with type safety and hierarchical JSON serialization
190 lines (189 loc) • 7.02 kB
JavaScript
;
/**
* Model-driven JSON mapping file processor for rawsql-ts integration.
* Handles detection and conversion of ModelDrivenJsonMapping formats.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.detectMappingFormat = detectMappingFormat;
exports.loadAndConvertMappingFile = loadAndConvertMappingFile;
exports.findAndConvertMappingFiles = findAndConvertMappingFiles;
exports.getMappingFileStats = getMappingFileStats;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const rawsql_ts_1 = require("rawsql-ts");
/**
* Detect the format of a JSON mapping file based on its structure.
*/
function detectMappingFormat(mappingData) {
// Check for ModelDrivenJsonMapping format
if (mappingData.typeInfo && mappingData.structure && typeof mappingData.structure === 'object') {
return 'model-driven';
}
// Check for legacy JsonMapping format
if (mappingData.rootName && mappingData.rootEntity && mappingData.rootEntity.name) {
return 'legacy';
}
return 'legacy'; // Default fallback
}
/**
* Load and convert a JSON mapping file to the standard JsonMapping format.
* Supports ModelDrivenJsonMapping format.
*/
function loadAndConvertMappingFile(filePath) {
if (!fs.existsSync(filePath)) {
throw new Error(`Mapping file not found: ${filePath}`);
}
const fileContent = fs.readFileSync(filePath, 'utf-8');
let mappingData;
try {
mappingData = JSON.parse(fileContent);
}
catch (error) {
throw new Error(`Invalid JSON in mapping file ${filePath}: ${error}`);
}
const format = detectMappingFormat(mappingData);
// Convert different formats to legacy format
let jsonMapping;
let typeProtection = { protectedStringFields: [] };
if (format === 'model-driven') {
// Convert Model-Driven format to legacy format
try {
const conversionResult = (0, rawsql_ts_1.convertModelDrivenMapping)(mappingData);
jsonMapping = conversionResult.jsonMapping;
typeProtection = conversionResult.typeProtection;
}
catch (error) {
throw new Error(`Failed to convert Model-Driven mapping ${filePath}: ${error}`);
}
}
else if (mappingData.rootName && mappingData.rootEntity) {
// Convert unified format to legacy format
jsonMapping = {
rootName: mappingData.rootName,
rootEntity: {
id: mappingData.rootEntity.id || 'root',
name: mappingData.rootEntity.name || mappingData.rootName,
columns: mappingData.rootEntity.columns || {}
},
nestedEntities: mappingData.nestedEntities || []
};
}
else {
// Assume it's already in legacy format
jsonMapping = mappingData;
}
return {
format,
jsonMapping,
typeProtection,
sourceFile: filePath,
success: true,
errors: [],
convertedMapping: jsonMapping
};
}
/**
* Search for mapping files in a directory and return conversion results.
* Supports multiple file naming patterns:
* - *.model-driven.json (ModelDrivenJsonMapping format)
* - *.json (legacy JsonMapping format)
*/
function findAndConvertMappingFiles(baseDir) {
const results = [];
if (!fs.existsSync(baseDir)) {
return results;
}
// Simple recursive file search
const searchDirectory = (dir) => {
const entries = fs.readdirSync(dir);
for (const entry of entries) {
const fullPath = path.join(dir, entry);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
searchDirectory(fullPath);
}
else if (stat.isFile() && entry.endsWith('.json')) {
// Skip common non-mapping JSON files
const nonMappingFiles = ['package.json', 'tsconfig.json', 'eslint.json', '.eslintrc.json', 'tsconfig.browser.json'];
if (nonMappingFiles.includes(entry)) {
continue;
}
// Process model-driven files
if (entry.endsWith('.model-driven.json')) {
try {
const result = loadAndConvertMappingFile(fullPath);
results.push(result);
}
catch (error) {
console.warn(`Failed to load model-driven mapping file ${fullPath}:`, error);
}
}
else if (!entry.includes('.model-driven.')) {
// Regular JSON file - try to detect format
try {
const result = loadAndConvertMappingFile(fullPath);
results.push(result);
}
catch (error) {
// Silently skip files that aren't mapping files
}
}
}
}
};
searchDirectory(baseDir);
return results;
}
/**
* Get mapping file statistics for a directory.
*/
function getMappingFileStats(baseDir) {
const results = findAndConvertMappingFiles(baseDir);
const stats = {
totalFiles: results.length,
byFormat: {
'model-driven': 0,
'unified': 0,
'legacy': 0
},
files: results.map(r => ({ path: r.sourceFile, format: r.format }))
};
for (const result of results) {
stats.byFormat[result.format]++;
}
return stats;
}
//# sourceMappingURL=MappingFileProcessor.js.map