myex-cli
Version:
Opinionated Express.js framework with CLI tools
57 lines (48 loc) • 1.88 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 } 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/service');
/**
* Generate a new service file
* @param {string} name - Service name
* @param {Object} options - Command options
*/
export async function generateService(name, options) {
const spinner = ora(`Generating service: ${chalk.blue(name)}`).start();
try {
// Ensure proper casing
const serviceName = camelCase(name) + 'Service';
const modelName = pascalCase(options.model || name);
const serviceFileName = `${camelCase(name)}.service.js`;
const destPath = path.join(process.cwd(), 'src', 'services', serviceFileName);
// Check if service already exists
if (fs.existsSync(destPath)) {
spinner.warn(chalk.yellow(`Service ${serviceFileName} already exists. Skipping.`));
return;
}
// Load template
const templateFile = path.join(templatesDir, 'service.template.ejs');
const template = await fs.readFile(templateFile, 'utf8');
// Render template
const content = ejs.render(template, {
serviceName,
serviceNameCamel: camelCase(name) + 'Service',
modelName,
modelNameCamel: camelCase(options.model || name),
name: camelCase(name)
});
// Create service file
await fs.ensureDir(path.dirname(destPath));
await fs.writeFile(destPath, content, 'utf8');
spinner.succeed(chalk.green(`Service generated: ${destPath}`));
} catch (error) {
spinner.fail(chalk.red(`Failed to generate service: ${error.message}`));
}
}