UNPKG

cl-generate

Version:

A cross-platform CLI tool to generate NestJS clean architecture modules

102 lines (94 loc) 3.21 kB
#!/usr/bin/env node const fs = require("fs").promises; const path = require("path"); // Colors for output const GREEN = "\x1b[32m"; const YELLOW = "\x1b[33m"; const RED = "\x1b[31m"; const NC = "\x1b[0m"; module.exports = async function removeModule( moduleNameLower, moduleNamePascal, moduleNameCapitalized ) { // Define directory paths const rootDir = "src"; const domainDir = path.join(rootDir, "domain"); const infraDir = path.join(rootDir, "infrastructure"); const useCasesDir = path.join(rootDir, "usecases"); // Function to remove file if exists async function removeFile(filePath) { try { if (await fs.stat(filePath).catch(() => false)) { await fs.unlink(filePath); console.log(`${GREEN}✔ Removed:${NC} ${filePath}`); } } catch (error) { console.error( `${RED}❌ Failed to remove:${NC} ${filePath} - ${error.message}` ); process.exit(1); } } // Function to remove directory if exists async function removeDir(dirPath) { try { if (await fs.stat(dirPath).catch(() => false)) { await fs.rm(dirPath, { recursive: true, force: true }); console.log(`${GREEN}✔ Removed directory:${NC} ${dirPath}`); } } catch (error) { console.error( `${RED}❌ Failed to remove directory:${NC} ${dirPath} - ${error.message}` ); process.exit(1); } } // Remove files await removeFile( path.join(domainDir, "repositories", `${moduleNameLower}.interface.ts`) ); await removeFile( path.join(domainDir, "models", `${moduleNameLower}.model.ts`) ); await removeFile(path.join(domainDir, "dtos", `${moduleNameLower}.dto.ts`)); await removeFile( path.join(infraDir, "entities", `${moduleNameLower}.entity.ts`) ); await removeFile( path.join(infraDir, moduleNameLower, `${moduleNameLower}.controller.ts`) ); await removeFile( path.join(infraDir, moduleNameLower, `${moduleNameLower}.repository.ts`) ); await removeFile( path.join(infraDir, moduleNameLower, `${moduleNameLower}.module.ts`) ); await removeFile(path.join(useCasesDir, `${moduleNameLower}.usecase.ts`)); await removeDir(path.join(infraDir, "repositories", moduleNameLower)); // Update app.module.ts const appModulePath = path.join(rootDir, "app.module.ts"); try { if (await fs.stat(appModulePath).catch(() => false)) { let appModuleContent = await fs.readFile(appModulePath, "utf8"); if (appModuleContent.includes(`${moduleNamePascal}Module`)) { appModuleContent = appModuleContent .replace( `import { ${moduleNamePascal}Module } from './infrastructure/${moduleNameLower}/${moduleNameLower}.module';\n`, "" ) .replace(`${moduleNamePascal}Module,`, "") .replace(`, ${moduleNamePascal}Module`, ""); await fs.writeFile(appModulePath, appModuleContent, "utf8"); console.log( `${GREEN}✔ Removed ${moduleNamePascal}Module from ${appModulePath}${NC}` ); } } } catch (error) { console.error( `${RED}❌ Failed to update ${appModulePath}:${NC} ${error.message}` ); process.exit(1); } };