UNPKG

myex-cli

Version:

Opinionated Express.js framework with CLI tools

59 lines (50 loc) 2.03 kB
import path from 'path'; import fs from 'fs-extra'; import chalk from 'chalk'; import ora from 'ora'; import { fileURLToPath } from 'url'; import ejs from 'ejs'; import { pascalCase, camelCase } from '../utils/string-utils.js'; // Convert ES Module path const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const templatesDir = path.resolve(__dirname, '../templates/controller'); /** * Generate a new controller file * @param {string} name - Controller name * @param {Object} options - Command options */ export async function generateController(name, options) { const spinner = ora(`Generating controller: ${chalk.blue(name)}`).start(); try { // Ensure proper casing const controllerName = camelCase(name) + 'Controller'; const modelName = pascalCase(options.model || name); const serviceName = camelCase(options.model || name) + 'Service'; const controllerFileName = `${camelCase(name)}.controller.js`; const destPath = path.join(process.cwd(), 'src', 'controllers', controllerFileName); // Check if controller already exists if (fs.existsSync(destPath)) { spinner.warn(chalk.yellow(`Controller ${controllerFileName} already exists. Skipping.`)); return; } // Load template const templateFile = path.join(templatesDir, 'controller.template.ejs'); const template = await fs.readFile(templateFile, 'utf8'); // Render template const content = ejs.render(template, { controllerName, controllerNameCamel: camelCase(name) + 'Controller', modelName, modelNameCamel: camelCase(options.model || name), serviceName, name: camelCase(name) }); // Create controller file await fs.ensureDir(path.dirname(destPath)); await fs.writeFile(destPath, content, 'utf8'); spinner.succeed(chalk.green(`Controller generated: ${destPath}`)); } catch (error) { spinner.fail(chalk.red(`Failed to generate controller: ${error.message}`)); } }