@diagramers/cli
Version:
Diagramers CLI - Command-line tools for managing Diagramers projects
325 lines • 18.3 kB
JavaScript
;
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.generateRelation = generateRelation;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
// Function to convert plural table names to singular for file names
function pluralToSingular(word) {
// Special cases for common words
const specialCases = {
'profiles': 'profile',
'categories': 'category',
'stories': 'story',
'series': 'series', // already singular
'species': 'species', // already singular
'analyses': 'analysis',
'bases': 'base',
'crises': 'crisis',
'diagnoses': 'diagnosis',
'ellipses': 'ellipsis',
'hypotheses': 'hypothesis',
'oases': 'oasis',
'parentheses': 'parenthesis',
'synopses': 'synopsis',
'theses': 'thesis'
};
// Check special cases first
if (specialCases[word]) {
return specialCases[word];
}
// Regular pluralization rules
if (word.endsWith('ies')) {
return word.slice(0, -3) + 'y'; // categories -> category
}
else if (word.endsWith('es')) {
return word.slice(0, -2); // boxes -> box
}
else if (word.endsWith('s')) {
return word.slice(0, -1); // users -> user, products -> product
}
return word; // already singular
}
async function generateRelation(moduleName, table1, table2, relationType = 'one-to-one', options = {}) {
// Validate module and table names
if (!moduleName || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(moduleName)) {
throw new Error('Invalid module name. Use only letters, numbers, hyphens, and underscores. Must start with a letter.');
}
if (!table1 || !table2 || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(table1) || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(table2)) {
throw new Error('Invalid table names. Use only letters, numbers, hyphens, and underscores. Must start with a letter.');
}
// Validate relation type
if (!['one-to-one', 'one-to-many', 'many-to-many'].includes(relationType)) {
throw new Error('Invalid relation type. Must be one of: one-to-one, one-to-many, many-to-many');
}
// Convert table names to singular for file names (consistent with table generator)
const table1Singular = pluralToSingular(table1);
const table2Singular = pluralToSingular(table2);
const table1Capitalized = table1Singular.charAt(0).toUpperCase() + table1Singular.slice(1);
const table2Capitalized = table2Singular.charAt(0).toUpperCase() + table2Singular.slice(1);
const currentDir = process.cwd();
// Check for required API project structure
const requiredDirs = ['src/modules'];
const missingDirs = requiredDirs.filter(dir => !fs.existsSync(path.join(currentDir, dir)));
if (missingDirs.length > 0) {
throw new Error(`This command should be run from a diagramers API project. Missing directories: ${missingDirs.join(', ')}`);
}
// Check if the module exists
const modulePath = path.join(currentDir, 'src/modules', moduleName);
if (!fs.existsSync(modulePath)) {
throw new Error(`Module '${moduleName}' does not exist. Please create the module first using: diagramers extend --module ${moduleName}`);
}
// Check if both tables exist in the same module (using singular names for file lookup)
const table1EntityPath = path.join(modulePath, 'entities', `${table1Singular}.entity.ts`);
const table2EntityPath = path.join(modulePath, 'entities', `${table2Singular}.entity.ts`);
const table1SchemaPath = path.join(modulePath, 'schemas', `${table1Singular}.schema.ts`);
const table2SchemaPath = path.join(modulePath, 'schemas', `${table2Singular}.schema.ts`);
if (!fs.existsSync(table1EntityPath) || !fs.existsSync(table1SchemaPath)) {
throw new Error(`Table '${table1}' does not exist in module '${moduleName}'. Please create the table first using: diagramers extend --table ${moduleName}:${table1}`);
}
if (!fs.existsSync(table2EntityPath) || !fs.existsSync(table2SchemaPath)) {
throw new Error(`Table '${table2}' does not exist in module '${moduleName}'. Please create the table first using: diagramers extend --table ${moduleName}:${table2}`);
}
// Check if relation already exists (basic check)
const table1Content = fs.readFileSync(table1EntityPath, 'utf8');
const table2Content = fs.readFileSync(table2EntityPath, 'utf8');
if (!options.force && (table1Content.includes(table2Capitalized) || table2Content.includes(table1Capitalized))) {
throw new Error(`Relationship between '${table1}' and '${table2}' already exists in module '${moduleName}'. Use --force to override.`);
}
console.log(`🔗 Creating ${relationType} relationship between ${table1} and ${table2} in module ${moduleName}...`);
// Update entities
console.log('📝 Updating entities...');
await updateEntity(path.join(modulePath, 'entities'), table1Singular, table1Capitalized, table2Capitalized, relationType, 'forward');
await updateEntity(path.join(modulePath, 'entities'), table2Singular, table2Capitalized, table1Capitalized, relationType, 'reverse');
// Update schemas
console.log('📋 Updating schemas...');
await updateSchema(path.join(modulePath, 'schemas'), table1Singular, table1Capitalized, table2Capitalized, relationType, 'forward');
await updateSchema(path.join(modulePath, 'schemas'), table2Singular, table2Capitalized, table1Capitalized, relationType, 'reverse');
console.log('✅ Relationship created successfully!');
console.log(`🔗 ${table1} ↔ ${table2} (${relationType}) in module ${moduleName}`);
console.log(`📁 Updated: src/modules/${moduleName}/entities/${table1Singular}.entity.ts`);
console.log(`📁 Updated: src/modules/${moduleName}/entities/${table2Singular}.entity.ts`);
console.log(`📁 Updated: src/modules/${moduleName}/schemas/${table1Singular}.schema.ts`);
console.log(`📁 Updated: src/modules/${moduleName}/schemas/${table2Singular}.schema.ts`);
}
async function updateEntity(entityPath, tableSingular, tableCapitalized, relatedTableCapitalized, relationType, direction) {
const entityFile = path.join(entityPath, `${tableSingular}.entity.ts`);
if (!fs.existsSync(entityFile)) {
console.warn(`⚠️ Entity file not found: ${entityFile}`);
return;
}
let entityContent = fs.readFileSync(entityFile, 'utf8');
// Add import for the related interface
const importStatement = `import { I${relatedTableCapitalized} } from '../${relatedTableCapitalized.toLowerCase()}.entity';`;
if (!entityContent.includes(importStatement)) {
// Find the last import statement and add after it
const importRegex = /import.*from.*['"];?\s*$/gm;
const matches = [...entityContent.matchAll(importRegex)];
if (matches.length > 0) {
const lastImport = matches[matches.length - 1];
const insertIndex = lastImport.index + lastImport[0].length;
entityContent = entityContent.slice(0, insertIndex) + '\n' + importStatement + entityContent.slice(insertIndex);
}
else {
// Add at the beginning if no imports exist
entityContent = importStatement + '\n\n' + entityContent;
}
}
// Find all interface blocks and merge their fields
const interfaceRegexGlobal = /export interface I\w+ extends mongoose\.Document \{([\s\S]*?)\}/g;
let allFields = [];
let match;
let firstInterfaceStart = -1;
let firstInterfaceEnd = -1;
let foundFirst = false;
while ((match = interfaceRegexGlobal.exec(entityContent)) !== null) {
if (!foundFirst) {
const fields = match[1].split('\n').map(line => line.trim()).filter(Boolean);
allFields.push(...fields);
firstInterfaceStart = match.index;
firstInterfaceEnd = interfaceRegexGlobal.lastIndex;
foundFirst = true;
}
// All other interface blocks will be removed
}
// Add new relationship fields
const newFields = generateEntityFields(tableCapitalized, relatedTableCapitalized, relationType, direction)
.split('\n').map(f => f.trim()).filter(Boolean);
allFields.push(...newFields);
// Deduplicate fields by name
const seen = new Set();
const dedupedFields = [];
for (const line of allFields) {
const fieldMatch = line.match(/^(\w+)/);
if (fieldMatch) {
const fieldName = fieldMatch[1];
if (!seen.has(fieldName)) {
seen.add(fieldName);
dedupedFields.push(line.replace(/[,;]*$/, ';'));
}
}
else {
dedupedFields.push(line);
}
}
// Build the new interface
const newInterface = `export interface ${tableCapitalized} extends BaseEntity {\n _id?: string;\n ${dedupedFields.join('\n ')}\n}`;
// Remove all old interface blocks and insert the new one at the position of the first
if (firstInterfaceStart !== -1 && firstInterfaceEnd !== -1) {
entityContent = entityContent.slice(0, firstInterfaceStart) + newInterface + entityContent.slice(firstInterfaceEnd);
// Remove any remaining interface blocks (if any)
entityContent = entityContent.replace(/export interface \w+ extends BaseEntity \{[\s\S]*?\}/g, newInterface);
}
fs.writeFileSync(entityFile, entityContent);
}
async function updateSchema(schemaPath, tableSingular, tableCapitalized, relatedTableCapitalized, relationType, direction) {
const schemaFile = path.join(schemaPath, `${tableSingular}.schema.ts`);
if (!fs.existsSync(schemaFile)) {
console.warn(`⚠️ Schema file not found: ${schemaFile}`);
return;
}
let schemaContent = fs.readFileSync(schemaFile, 'utf8');
// Add import for the related schema
const importStatement = `import { ${relatedTableCapitalized}Entity } from '../${relatedTableCapitalized.toLowerCase()}.schema';`;
if (!schemaContent.includes(importStatement)) {
// Find the last import statement and add after it
const importRegex = /import.*from.*['"];?\s*$/gm;
const matches = [...schemaContent.matchAll(importRegex)];
if (matches.length > 0) {
const lastImport = matches[matches.length - 1];
const insertIndex = lastImport.index + lastImport[0].length;
schemaContent = schemaContent.slice(0, insertIndex) + '\n' + importStatement + schemaContent.slice(insertIndex);
}
else {
// Add at the beginning if no imports exist
schemaContent = importStatement + '\n\n' + schemaContent;
}
}
// Add schema fields based on relationship type
const schemaRegex = /export const \w+Schema = new mongoose\.Schema\((\{[\s\S]*?\}),/s;
const match = schemaContent.match(schemaRegex);
if (match) {
let schemaFields = match[1];
const newFields = generateSchemaFields(tableSingular, relatedTableCapitalized, relationType, direction);
if (newFields) {
// Insert new fields before the closing brace of the schema object
schemaFields = schemaFields.replace(/\}$/, ` ${newFields}\n}`);
schemaContent = schemaContent.replace(schemaRegex, `export const ${tableSingular}Schema = new mongoose.Schema(${schemaFields},`);
}
}
fs.writeFileSync(schemaFile, schemaContent);
}
function generateEntityFields(tableCapitalized, relatedTableCapitalized, relationType, direction) {
switch (relationType) {
case 'one-to-one':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Id: string;\n ${relatedTableCapitalized.toLowerCase()}?: I${relatedTableCapitalized};`;
}
else {
return `${tableCapitalized.toLowerCase()}Id: string;\n ${tableCapitalized.toLowerCase()}?: I${tableCapitalized};`;
}
case 'one-to-many':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Id: string;\n ${relatedTableCapitalized.toLowerCase()}?: I${relatedTableCapitalized};`;
}
else {
return `${tableCapitalized.toLowerCase()}s?: I${tableCapitalized}[];`;
}
case 'many-to-many':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Ids: string[];\n ${relatedTableCapitalized.toLowerCase()}s?: I${relatedTableCapitalized}[];`;
}
else {
return `${tableCapitalized.toLowerCase()}Ids: string[];\n ${tableCapitalized.toLowerCase()}s?: I${tableCapitalized}[];`;
}
default:
return '';
}
}
function generateSchemaFields(tableSingular, relatedTableCapitalized, relationType, direction) {
switch (relationType) {
case 'one-to-one':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Id: {\n type: String,\n ref: '${relatedTableCapitalized.toLowerCase()}',\n required: false\n }`;
}
else {
return `${tableSingular.toLowerCase()}Id: {\n type: String,\n ref: '${tableSingular.toLowerCase()}',\n required: false\n }`;
}
case 'one-to-many':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Id: {\n type: String,\n ref: '${relatedTableCapitalized.toLowerCase()}',\n required: false\n }`;
}
else {
return ''; // No field needed for reverse one-to-many
}
case 'many-to-many':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Ids: [{\n type: String,\n ref: '${relatedTableCapitalized.toLowerCase()}'\n }]`;
}
else {
return `${tableSingular.toLowerCase()}Ids: [{\n type: String,\n ref: '${tableSingular.toLowerCase()}'\n }]`;
}
default:
return '';
}
}
function generateVirtualFields(tableCapitalized, relatedTableCapitalized, relationType, direction) {
switch (relationType) {
case 'one-to-one':
if (direction === 'forward') {
return `// Virtual populate for ${relatedTableCapitalized.toLowerCase()}\n${tableCapitalized.toLowerCase()}Schema.virtual('${relatedTableCapitalized.toLowerCase()}', {\n ref: '${relatedTableCapitalized.toLowerCase()}',\n localField: '${relatedTableCapitalized.toLowerCase()}Id',\n foreignField: '_id',\n justOne: true\n});`;
}
else {
return `// Virtual populate for ${tableCapitalized.toLowerCase()}\n${tableCapitalized.toLowerCase()}Schema.virtual('${tableCapitalized.toLowerCase()}', {\n ref: '${tableCapitalized.toLowerCase()}',\n localField: '${tableCapitalized.toLowerCase()}Id',\n foreignField: '_id',\n justOne: true\n});`;
}
case 'one-to-many':
if (direction === 'forward') {
return `// Virtual populate for ${relatedTableCapitalized.toLowerCase()}\n${tableCapitalized.toLowerCase()}Schema.virtual('${relatedTableCapitalized.toLowerCase()}', {\n ref: '${relatedTableCapitalized.toLowerCase()}',\n localField: '${relatedTableCapitalized.toLowerCase()}Id',\n foreignField: '_id',\n justOne: true\n});`;
}
else {
return `// Virtual populate for ${tableCapitalized.toLowerCase()}s\n${tableCapitalized.toLowerCase()}Schema.virtual('${tableCapitalized.toLowerCase()}s', {\n ref: '${tableCapitalized.toLowerCase()}',\n localField: '_id',\n foreignField: '${tableCapitalized.toLowerCase()}Id'\n});`;
}
case 'many-to-many':
if (direction === 'forward') {
return `// Virtual populate for ${relatedTableCapitalized.toLowerCase()}s\n${tableCapitalized.toLowerCase()}Schema.virtual('${relatedTableCapitalized.toLowerCase()}s', {\n ref: '${relatedTableCapitalized.toLowerCase()}',\n localField: '${relatedTableCapitalized.toLowerCase()}Ids',\n foreignField: '_id'\n});`;
}
else {
return `// Virtual populate for ${tableCapitalized.toLowerCase()}s\n${tableCapitalized.toLowerCase()}Schema.virtual('${tableCapitalized.toLowerCase()}s', {\n ref: '${tableCapitalized.toLowerCase()}',\n localField: '${tableCapitalized.toLowerCase()}Ids',\n foreignField: '_id'\n});`;
}
default:
return '';
}
}
//# sourceMappingURL=relation-generator.js.map