@diagramers/cli
Version:
Diagramers CLI - Command-line tools for managing Diagramers projects
230 lines • 13.8 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"));
async function generateRelation(table1, table2, relationType = 'one-to-one') {
// Validate table names
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.');
}
const table1Capitalized = table1.charAt(0).toUpperCase() + table1.slice(1);
const table2Capitalized = table2.charAt(0).toUpperCase() + table2.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 both modules exist
const table1ModulePath = path.join(currentDir, 'src/modules', table1);
const table2ModulePath = path.join(currentDir, 'src/modules', table2);
if (!fs.existsSync(table1ModulePath) || !fs.existsSync(table2ModulePath)) {
throw new Error(`Both modules must exist before creating relationships. Missing: ${!fs.existsSync(table1ModulePath) ? table1 : ''} ${!fs.existsSync(table2ModulePath) ? table2 : ''}`);
}
console.log(`🔗 Creating ${relationType} relationship between ${table1} and ${table2}...`);
// Update entities
console.log('📝 Updating entities...');
await updateEntity(path.join(table1ModulePath, 'entities'), table1Capitalized, table2Capitalized, relationType, 'forward');
await updateEntity(path.join(table2ModulePath, 'entities'), table2Capitalized, table1Capitalized, relationType, 'reverse');
// Update schemas
console.log('📋 Updating schemas...');
await updateSchema(path.join(table1ModulePath, 'schemas'), table1Capitalized, table2Capitalized, relationType, 'forward');
await updateSchema(path.join(table2ModulePath, 'schemas'), table2Capitalized, table1Capitalized, relationType, 'reverse');
console.log('✅ Relationship created successfully!');
console.log(`🔗 ${table1} ↔ ${table2} (${relationType})`);
}
async function updateEntity(entityPath, tableCapitalized, relatedTableCapitalized, relationType, direction) {
const entityFile = path.join(entityPath, `${tableCapitalized.toLowerCase()}.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;
}
}
// Add relationship fields based on type
const interfaceRegex = /export interface I\w+ extends mongoose\.Document \{([^}]*)\}/s;
const match = entityContent.match(interfaceRegex);
if (match) {
const interfaceContent = match[1];
const newFields = generateEntityFields(tableCapitalized, relatedTableCapitalized, relationType, direction);
// Add new fields before the closing brace
const updatedInterfaceContent = interfaceContent.trim() + '\n ' + newFields;
entityContent = entityContent.replace(interfaceRegex, `export interface I${tableCapitalized} extends mongoose.Document {$1${updatedInterfaceContent}\n}`);
}
fs.writeFileSync(entityFile, entityContent);
}
async function updateSchema(schemaPath, tableCapitalized, relatedTableCapitalized, relationType, direction) {
const schemaFile = path.join(schemaPath, `${tableCapitalized.toLowerCase()}.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;
const match = schemaContent.match(schemaRegex);
if (match) {
const schemaFields = match[1];
const newFields = generateSchemaFields(tableCapitalized, relatedTableCapitalized, relationType, direction);
if (newFields) {
// Add new fields before the closing brace
const updatedSchemaFields = schemaFields.trim() + '\n ' + newFields;
schemaContent = schemaContent.replace(schemaRegex, `export const ${tableCapitalized.toLowerCase()}Schema = new mongoose.Schema(${updatedSchemaFields},`);
}
}
// Add virtual fields and population methods
const modelRegex = /export const \w+Entity = mongoose\.model<.*>\(.*\);?\s*$/;
const virtualFields = generateVirtualFields(tableCapitalized, relatedTableCapitalized, relationType, direction);
if (virtualFields) {
schemaContent = schemaContent.replace(modelRegex, `${virtualFields}\n\n$&`);
}
fs.writeFileSync(schemaFile, schemaContent);
}
function generateEntityFields(tableCapitalized, relatedTableCapitalized, relationType, direction) {
switch (relationType) {
case 'one-to-one':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Id: ObjectId,\n ${relatedTableCapitalized.toLowerCase()}?: I${relatedTableCapitalized}`;
}
else {
return `${tableCapitalized.toLowerCase()}Id: ObjectId,\n ${tableCapitalized.toLowerCase()}?: I${tableCapitalized}`;
}
case 'one-to-many':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Id: ObjectId,\n ${relatedTableCapitalized.toLowerCase()}?: I${relatedTableCapitalized}`;
}
else {
return `${tableCapitalized.toLowerCase()}s?: I${tableCapitalized}[]`;
}
case 'many-to-many':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Ids: ObjectId[],\n ${relatedTableCapitalized.toLowerCase()}s?: I${relatedTableCapitalized}[]`;
}
else {
return `${tableCapitalized.toLowerCase()}Ids: ObjectId[],\n ${tableCapitalized.toLowerCase()}s?: I${tableCapitalized}[]`;
}
default:
return '';
}
}
function generateSchemaFields(tableCapitalized, relatedTableCapitalized, relationType, direction) {
switch (relationType) {
case 'one-to-one':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Id: {\n type: mongoose.SchemaTypes.ObjectId,\n ref: '${relatedTableCapitalized.toLowerCase()}',\n required: false\n }`;
}
else {
return `${tableCapitalized.toLowerCase()}Id: {\n type: mongoose.SchemaTypes.ObjectId,\n ref: '${tableCapitalized.toLowerCase()}',\n required: false\n }`;
}
case 'one-to-many':
if (direction === 'forward') {
return `${relatedTableCapitalized.toLowerCase()}Id: {\n type: mongoose.SchemaTypes.ObjectId,\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: mongoose.SchemaTypes.ObjectId,\n ref: '${relatedTableCapitalized.toLowerCase()}'\n }]`;
}
else {
return `${tableCapitalized.toLowerCase()}Ids: [{\n type: mongoose.SchemaTypes.ObjectId,\n ref: '${tableCapitalized.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