dynamic-orm
Version:
A flexible and powerful dynamic ORM for SQL databases with Redis caching support and many-to-many relationship handling
205 lines (169 loc) ā¢ 6.07 kB
JavaScript
/**
* This script helps users initialize the dynamic-orm package in their project
* It creates configuration files and examples
*/
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Ensure the scripts directory exists
if (!fs.existsSync('scripts')) {
fs.mkdirSync('scripts', { recursive: true });
}
console.log('=== Dynamic ORM Initialization ===');
console.log('This script will help you set up dynamic-orm in your project.\n');
// Ask questions to configure the package
rl.question('Where is your database configuration file? (e.g., src/config/db.config.js): ', (dbPath) => {
rl.question('Where is your Redis configuration file? (e.g., src/config/redis.js): ', (redisPath) => {
rl.question('Where would you like to create the ORM configuration? (e.g., src/config/orm.js): ', (ormPath) => {
rl.question('Would you like to use Redis caching? (yes/no): ', (useCache) => {
// Create the ORM configuration file
createOrmConfig(dbPath, redisPath, ormPath, useCache.toLowerCase() === 'yes');
// Create example model
rl.question('Would you like to create an example model? (yes/no): ', (createExample) => {
if (createExample.toLowerCase() === 'yes') {
rl.question('Table name for the example model: ', (tableName) => {
rl.question('Primary key field name (default: id): ', (primaryKey) => {
rl.question('Where to create the example model? (e.g., src/models/exampleModel.js): ', (modelPath) => {
createExampleModel(tableName, primaryKey || 'id', modelPath, ormPath);
rl.close();
});
});
});
} else {
rl.close();
}
});
});
});
});
});
function createOrmConfig(dbPath, redisPath, ormPath, useCache) {
// Convert path to relative import
const dbImport = pathToImport(dbPath);
const redisImport = pathToImport(redisPath);
// Create the ORM configuration
const ormContent = `/**
* Dynamic ORM configuration
* Generated by dynamic-orm initialization script
*/
const { createORM } = require('dynamic-orm');
const { prepare, transaction } = require('${dbImport}');
${useCache ? `const { redis } = require('${redisImport}');` : ''}
/**
* ORM factory for creating database models
*/
const orm = createORM({
db: { prepare, transaction },
${useCache ? 'redis,' : ''}
useCache: ${useCache}
});
module.exports = { orm };
`;
// Create the directory if it doesn't exist
const ormDir = path.dirname(ormPath);
if (!fs.existsSync(ormDir)) {
fs.mkdirSync(ormDir, { recursive: true });
}
// Write the configuration file
fs.writeFileSync(ormPath, ormContent);
console.log(`ā
ORM configuration created at: ${ormPath}`);
}
function createExampleModel(tableName, primaryKey, modelPath, ormPath) {
// Convert path to relative import
const ormImport = pathToImport(ormPath);
// Create the model content
const modelNameCamel = tableName.charAt(0).toLowerCase() + tableName.slice(1);
const modelNamePascal = tableName.charAt(0).toUpperCase() + tableName.slice(1);
const modelContent = `/**
* ${modelNamePascal} model
* Generated by dynamic-orm initialization script
*/
const { orm } = require('${ormImport}');
/**
* ${modelNamePascal} database model
* Table: ${tableName}
*/
const ${modelNameCamel}Model = orm.createModel('${tableName}', {
primaryKey: '${primaryKey}',
// Add your configuration options here
// searchableFields: ['name', 'description'],
// cacheTTL: 3600,
// defaultLimit: 50
});
module.exports = ${modelNameCamel}Model;
`;
// Create the directory if it doesn't exist
const modelDir = path.dirname(modelPath);
if (!fs.existsSync(modelDir)) {
fs.mkdirSync(modelDir, { recursive: true });
}
// Write the model file
fs.writeFileSync(modelPath, modelContent);
console.log(`ā
Example model created at: ${modelPath}`);
// Create example usage
const exampleContent = `/**
* ${modelNamePascal} usage examples
* Generated by dynamic-orm initialization script
*/
const ${modelNameCamel}Model = require('${pathToImport(modelPath)}');
/**
* Find all ${tableName}
*/
async function findAll${modelNamePascal}s(options = {}) {
return ${modelNameCamel}Model.findAll(options);
}
/**
* Find ${modelNameCamel} by ID
*/
async function find${modelNamePascal}ById(id) {
return ${modelNameCamel}Model.findById(id);
}
/**
* Create a new ${modelNameCamel}
*/
async function create${modelNamePascal}(data) {
return ${modelNameCamel}Model.create(data);
}
/**
* Update a ${modelNameCamel}
*/
async function update${modelNamePascal}(id, data) {
return ${modelNameCamel}Model.update(id, data);
}
/**
* Delete a ${modelNameCamel}
*/
async function delete${modelNamePascal}(id) {
return ${modelNameCamel}Model.delete(id);
}
module.exports = {
findAll${modelNamePascal}s,
find${modelNamePascal}ById,
create${modelNamePascal},
update${modelNamePascal},
delete${modelNamePascal}
};
`;
// Create the example usage file
const examplePath = path.join(modelDir, `${modelNameCamel}Service.js`);
fs.writeFileSync(examplePath, exampleContent);
console.log(`ā
Example service created at: ${examplePath}`);
console.log('\nš Initialization complete! You can now use dynamic-orm in your project.');
console.log(` To get started, import your model: const ${modelNameCamel}Model = require('${pathToImport(modelPath)}');`);
}
function pathToImport(filePath) {
// Convert Windows path to Unix-style path
let normalizedPath = filePath.replace(/\\/g, '/');
// Remove file extension
normalizedPath = normalizedPath.replace(/\.[^/.]+$/, '');
// If path doesn't start with ./ or ../, add ./
if (!normalizedPath.startsWith('./') && !normalizedPath.startsWith('../')) {
normalizedPath = './' + normalizedPath;
}
return normalizedPath;
}