myex-cli
Version:
Opinionated Express.js framework with CLI tools
57 lines (48 loc) • 1.9 kB
JavaScript
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, pluralize } 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/route');
/**
* Generate a new route file
* @param {string} name - Route name
* @param {Object} options - Command options
*/
export async function generateRoute(name, options) {
const spinner = ora(`Generating route: ${chalk.blue(name)}`).start();
try {
// Ensure proper casing
const routeName = camelCase(name) + 'Routes';
const controllerName = camelCase(options.controller || name) + 'Controller';
const routeFileName = `${camelCase(name)}.routes.js`;
const destPath = path.join(process.cwd(), 'src', 'routes', routeFileName);
// Check if route already exists
if (fs.existsSync(destPath)) {
spinner.warn(chalk.yellow(`Route ${routeFileName} already exists. Skipping.`));
return;
}
// Load template
const templateFile = path.join(templatesDir, 'route.template.ejs');
const template = await fs.readFile(templateFile, 'utf8');
// Render template
const content = ejs.render(template, {
routeName,
controllerName,
controllerNameCamel: camelCase(options.controller || name) + 'Controller',
name: camelCase(name),
namePlural: pluralize(camelCase(name))
});
// Create route file
await fs.ensureDir(path.dirname(destPath));
await fs.writeFile(destPath, content, 'utf8');
spinner.succeed(chalk.green(`Route generated: ${destPath}`));
} catch (error) {
spinner.fail(chalk.red(`Failed to generate route: ${error.message}`));
}
}