Package Exports
- ucg
- ucg/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (ucg) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
UCG - Universal CRUD Generator 🚀
🏆 Enterprise RBAC with Microservice Architecture - The most advanced Node.js API generator. Create complete REST APIs with enterprise-grade authentication, multi-company support, and scalable microservice architecture. One command to production-ready APIs.
🎊 NEW: Enterprise Microservice Architecture (v1.2.0-beta.7)
# 🚀 Create Enterprise API with Microservices in 3 commands
npm install -g ucg@1.2.0-beta.7
ucg init --auto
ucg generate:auth --features rbac,company,email,workers,swagger
# ✨ Generates: 13 Microservices + Enterprise RBAC + Multi-Company + 60% Performance Boost🎯 What Makes UCG Special?
🏗️ Microservice Architecture (NEW!)
- 13 Focused Services: Each service handles specific domain logic (200-500 lines vs 2000+ monolithic)
- Service Orchestrator: Unified API interface with
services.user.profile.*,services.role.templates.* - Independent Scaling: Scale services individually based on demand
- Parallel Processing: 60% performance improvement through concurrent execution
🔒 Enterprise RBAC System
- Role Templates: Global role definitions managed by system admins
- Company Customization: Each company can customize roles and permissions
- Permission Groups: Batch permission management for easier administration
- Multi-Company Users: Users can have different roles across multiple companies
- Context-Aware Access: Dynamic permissions based on user's current company context
⚡ Performance & Scalability
- 60% Faster: Dashboard loading through parallel microservice execution
- Optimized Queries: Each service optimizes its own database access patterns
- Independent Caching: Service-specific caching strategies
- Horizontal Scaling: Deploy and scale services independently
📦 Installation
🔥 Latest Beta (Recommended)
# Install latest beta with migration auto-execution fix
npm install -g ucg@beta
# Or for project-specific installation
npm install ucg@beta
# Verify beta installation
ucg --version # Should show v1.2.0-beta.4🛡️ Stable Release
# Global CLI installation (stable)
npm install -g ucg
# Project plugin installation (stable)
npm install ucg⚡ Quick Project Setup
# Create new project with UCG pre-configured
npx ucg@beta quick-setup --name my-api --db postgres
cd my-api && npm start
# Or use the latest beta
npx ucg@beta generate:auth --features rbac,company,email🚀 Quick Start
One-Command Setup
# Create a complete API in 30 seconds
npx ucg generate user
# ✨ Generated: Model + Controller + Routes + Validation + Tests + SwaggerInteractive CLI Setup
npm install -g ucg
ucg init # Initialize project with database config
ucg generate # Interactive model/CRUD generation wizard
ucg start # Launch admin dashboard at http://localhost:3000🔌 Express.js Plugin Integration
Basic Plugin Setup
const express = require('express');
const { UCGPlugin } = require('ucg');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Create UCG plugin instance
const ucgPlugin = new UCGPlugin({
mountPath: '/ucg',
autoRegisterRoutes: true,
swaggerConfig: {
title: 'My API Documentation',
version: '1.0.0',
description: 'Auto-generated API with UCG'
}
});
// Mount the plugin
app.use('/ucg', ucgPlugin.initialize(app));
app.listen(3000, () => {
console.log('🚀 Server: http://localhost:3000');
console.log('🎨 UCG Admin: http://localhost:3000/ucg/');
console.log('📚 API Docs: http://localhost:3000/ucg/docs/');
});Advanced Plugin Configuration
const express = require('express');
const { UCGPlugin } = require('ucg');
const app = express();
// Advanced UCG configuration
const ucgPlugin = new UCGPlugin({
mountPath: '/admin',
autoRegisterRoutes: true,
// Database configuration (auto-detected from .env)
database: {
type: 'postgres',
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || 5432,
database: process.env.DB_NAME,
username: process.env.DB_USER,
password: process.env.DB_PASSWORD
},
// Authentication & RBAC
auth: {
enabled: true,
jwtSecret: process.env.JWT_SECRET,
rbac: true,
multiCompany: true
},
// Swagger documentation
swaggerConfig: {
title: 'Enterprise API',
version: '1.0.0',
description: 'Complete REST API with UCG',
contact: {
name: 'API Support',
email: 'support@example.com'
}
},
// CORS and security
cors: {
origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
credentials: true
}
});
// Error handling wrapper
try {
app.use('/admin', ucgPlugin.initialize(app));
console.log('✅ UCG Plugin integrated successfully');
} catch (error) {
console.error('❌ UCG Plugin integration failed:', error.message);
console.log('⚠️ Running without UCG functionality');
}
app.listen(3000);Environment Configuration (.env)
# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp_db
DB_USER=postgres
DB_PASSWORD=password
DB_DIALECT=postgres
# UCG Configuration
JWT_SECRET=your-super-secret-jwt-key
MASTER_ENCRYPTION_KEY=your-32-char-encryption-key
TABLE_PREFIX=app_
# Server Configuration
PORT=3000
NODE_ENV=development
CORS_ORIGIN=http://localhost:3000💡 What UCG Generates
Command: ucg generate:crud --model User
Generated Structure:
src/
├── models/User.js # Sequelize model with associations
├── controllers/userController.js # CRUD operations with error handling
├── routes/userRoutes.js # Express routes with validation middleware
├── validators/userValidator.js # Joi input validation schemas
├── services/userService.js # Business logic layer (optional)
├── docs/swagger/user.swagger.js # OpenAPI/Swagger documentation
└── tests/user.test.js # Jest unit tests with mocksGenerated API Endpoints:
- GET
/api/users- List all users with pagination - GET
/api/users/:id- Get user by ID with relational data - POST
/api/users- Create new user with validation - PUT
/api/users/:id- Update user - DELETE
/api/users/:id- Delete user
Generated Controller Sample:
// src/controllers/userController.js
const { User } = require('../models');
const userValidator = require('../validators/userValidator');
class UserController {
async getAll(req, res) {
try {
const { page = 1, limit = 10 } = req.query;
const users = await User.findAndCountAll({
limit: parseInt(limit),
offset: (page - 1) * limit,
include: ['profile', 'posts'] // Auto-detected relations
});
res.json({
success: true,
data: users.rows,
pagination: {
total: users.count,
page: parseInt(page),
pages: Math.ceil(users.count / limit)
}
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
}
// ... other CRUD methods
}⭐ Key Features
🚀 Lightning Fast Development
- 1-Command Setup:
npx ucg generate usercreates complete API - Auto-Detection: Analyzes database schema and generates models automatically
- Live Preview: See generated code before writing files
- Hot Reload: Changes auto-restart server with new routes
🎯 Production Ready
- Input Validation: Joi schemas for request validation
- Error Handling: Standardized error responses with status codes
- Security: Helmet, CORS, and rate limiting built-in
- Logging: Morgan HTTP request logging
- Testing: Jest unit tests with mocks and fixtures
🔧 Developer Experience
- Admin Dashboard: Web interface for visual model/CRUD generation
- Interactive CLI: Step-by-step guided setup
- TypeScript Support: Full type definitions included
- Swagger Integration: Auto-generated OpenAPI docs
- VS Code Ready: IntelliSense and debugging support
🏗️ Enterprise Features
- Multiple ORMs: Sequelize, TypeORM, Knex.js support
- Database Agnostic: PostgreSQL, MySQL, SQLite compatibility
- Plugin Architecture: Extensible with custom templates
- CI/CD Ready: GitHub Actions, Docker, and deployment configs
🗄️ Database Support
| Database | ORM Support | Status |
|---|---|---|
| PostgreSQL | Sequelize, TypeORM, Knex.js | ✅ Full Support |
| MySQL/MariaDB | Sequelize, TypeORM, Knex.js | ✅ Full Support |
| SQLite | Sequelize, TypeORM, Knex.js | ✅ Full Support |
| MongoDB | Mongoose | 🔄 Coming Soon |
ORM Examples
Sequelize (Default):
ucg generate:crud --model User --orm sequelize
# Generates: Sequelize models with associations, hooks, and scopesTypeORM:
ucg generate:crud --model User --orm typeorm
# Generates: TypeORM entities with decorators and repositoriesKnex.js:
ucg generate:crud --model User --orm knex
# Generates: Knex query builders and migrations🎛️ CLI Commands
Interactive Mode
ucg init # Interactive project setup
ucg generate # Interactive model/CRUD generation
ucg start # Launch admin dashboardAutomation Mode
# Model generation
ucg generate:model --table users --output src/models
# CRUD generation with specific operations
ucg generate:crud --model User --operations create,read,update
# Preview without writing files
ucg generate:crud --model User --preview --dry-run
# Generate with custom templates
ucg generate:crud --model User --template custom-api🛠️ Troubleshooting
Common Issues
1. API Routes Return 404 Errors
Symptoms: Generated routes appear in Swagger docs but return 404 when accessed.
Causes & Solutions:
Sequelize Alias Conflicts: Multiple foreign keys to the same table using identical aliases.
# Error message: # "You have used the alias 'questions' in two separate associations"
Solution: UCG v1.1.5+ automatically generates unique aliases. Update your UCG version:
npm update ucgRoute Mounting Issues: Routes not properly integrated into Express app. Solution: Ensure
autoRegisterRoutes: trueis set and restart your server.
2. CORS Errors in Swagger UI
Symptoms: "Failed to fetch" errors when testing APIs in Swagger documentation.
Solution: Add CORS middleware to your Express app:
const cors = require('cors');
app.use(cors({
origin: true,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
}));3. Database Connection Issues
Symptoms: UCG admin interface shows database connection errors.
Solutions:
- Verify database credentials in UCG setup
- Ensure database server is running
- Check network connectivity to database host
4. PostgreSQL First-Time Setup Issues
Symptoms: "Database connection failed" or "Table not found" errors when generating CRUD for the first time.
Common Issues & Solutions:
ECONNREFUSED: PostgreSQL server not running
# Start PostgreSQL (macOS with Homebrew) brew services start postgresql # Start PostgreSQL (Ubuntu/Debian) sudo systemctl start postgresql
Authentication Failed (28P01): Incorrect credentials
# Check PostgreSQL user and password psql -U your_username -d your_database
Database Does Not Exist (3D000): Database not created
-- Connect to PostgreSQL and create database psql -U postgres CREATE DATABASE your_database_name;Connection Timeout: Check host and port settings in UCG configuration
Getting Help
If you encounter issues:
- Check the GitHub Issues
- Review the error logs in your console
- Ensure you're using the latest UCG version:
npm update ucg
🔧 Troubleshooting Beta Version
❌ Common Issues & Solutions
Migration Not Running Automatically
# Symptoms
✅ Migration files generated
❌ Database tables not created
❌ "Migration completed with warnings"
# Solution 1: Check database connection
psql -h $DB_HOST -U $DB_USER -d $DB_NAME -c "SELECT 1;"
# Solution 2: Ensure environment variables are set
echo $DB_HOST $DB_PORT $DB_NAME $DB_USER
# Solution 3: Run migration manually (fallback)
cd src/database && npx sequelize-cli db:migrate
# Solution 4: Use alternative migration approach
npx ucg@beta generate:auth --features rbac --database-url postgresql://user:pass@localhost:5432/dbnamePlugin Integration Issues
# Symptoms
❌ "UCG Plugin integration failed"
❌ "Cannot find module 'ucg'"
# Solution 1: Verify beta installation
npm list ucg
# Should show: ucg@1.2.0-beta.4
# Solution 2: Reinstall beta version
npm uninstall ucg
npm install ucg@beta
# Solution 3: Use correct import syntax
const { UCGPlugin } = require('ucg'); // ✅ Correct
const ucg = require('ucg'); // ❌ Old syntaxDatabase Connection Issues
# Symptoms
❌ "Database not configured, skipping migrations"
❌ Connection timeout or authentication failed
# Solution 1: Test database connectivity
node -e "
const { Sequelize } = require('sequelize');
const db = new Sequelize(process.env.DATABASE_URL || {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_NAME,
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
dialect: 'postgres'
});
db.authenticate().then(() => console.log('✅ Connected')).catch(err => console.error('❌', err));
"
# Solution 2: Check .env file is loaded
node -e "require('dotenv').config(); console.log('DB_HOST:', process.env.DB_HOST);"
# Solution 3: Use DATABASE_URL format
export DATABASE_URL="postgresql://user:password@localhost:5432/database"🛠️ Debug Mode
# Enable verbose logging
DEBUG=ucg:* npx ucg@beta generate:auth --features rbac,company
# Check UCG version and health
ucg --version
ucg health
# Test database connection
ucg status📞 Getting Help
# Check official documentation
ucg --help
ucg generate:auth --help
# View generated files structure
ucg generate:auth --preview --features rbac,company
# Community support
# GitHub Issues: https://github.com/jithvar/ucg/issues
# Documentation: https://www.npmjs.com/package/ucg📦 Publishing & Deployment
🚀 Deploy Beta to NPM
# 1. Verify changes and tests
npm test
# 2. Update version (already done: v1.2.0-beta.4)
cat package.json | grep version
# 3. Build and publish beta
npm run build # if applicable
npm publish --tag beta
# 4. Verify publication
npm view ucg@beta version
npm view ucg dist-tags
# 5. Test installation
npm install -g ucg@beta
ucg --version # Should show v1.2.0-beta.4📋 Pre-Publishing Checklist
- ✅ Migration auto-execution tested and working
- ✅ Database tables created automatically
- ✅ Admin user seeded successfully
- ✅ Plugin integration works in Express.js
- ✅ PostgreSQL, MySQL, SQLite support verified
- ✅ README updated with plugin instructions
- ✅ Beta version tagged appropriately
🎯 Post-Publishing Verification
# Test fresh installation from npm
npm install -g ucg@beta
# Create test project
mkdir npm-test && cd npm-test
npm init -y
npm install express ucg@beta
# Test complete workflow
ucg generate:auth --features rbac,company,email
# Should complete without errors and create database tables🤝 Contributing
Local Development Setup
# Clone the repository
git clone https://github.com/jithvar/ucg.git
cd ucg
# Install dependencies
npm install
# Run tests
npm test
# Start local development server
npm run devSubmitting Pull Requests
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
UCG is currently free to use under our Free Tier License.
Future Licensing Notice: Jithvar Consultancy Services may introduce paid subscription tiers for enhanced features, enterprise support, and commercial usage in future versions. Current users will be notified of any licensing changes with adequate transition period.
For enterprise support or custom development: Contact Jithvar
🙏 Support & Links
- 🏠 Homepage: UCG on GitHub
- 📦 NPM Package: ucg on npmjs
- 📚 Documentation: Available in admin interface (
/admin/docs) - 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
- 🆕 Changelog: CHANGELOG.md
- 📄 License: Free Tier License
- 🏢 Enterprise: Jithvar Consultancy Services
Stay Updated
- ⭐ Star the repo for updates
- 👀 Watch releases for new features
- 🌐 Visit: jithvar.com
Performance & Analytics
- 📊 Weekly Downloads:
- 📈 Total Downloads:
- ⚡ Bundle Size:
Developed by Jithvar Consultancy Services
Transform your Express.js development workflow. Generate production-ready APIs in seconds.
📝 Changelog
v1.2.0-beta.4 (Latest) - Migration Auto-Execution Fix
🔥 CRITICAL FIX: Database migrations now run automatically
✅ Fixed:
- Migration auto-execution during auth generation
- Database tables now created automatically
- Initial data seeding works properly
- Proper MigrationRunner integration
✅ Improved:
- Enhanced error handling with fallback mechanisms
- Better database configuration validation
- Comprehensive logging for debugging
- Multi-database support (PostgreSQL, MySQL, SQLite)
🎯 New Features:
- Complete RBAC system with auto-migration
- Multi-company/tenant support
- Email verification system
- Admin dashboard improvements
🛠️ Technical Changes:
- Updated
runMigrations()to useMigrationRunner.runMigrations() - Updated
runSeeders()to useMigrationRunner.seedDatabase() - Added fallback migration execution for error recovery
- Enhanced database configuration passing
v1.2.0-beta.3 - Authentication System
- Added comprehensive authentication system
- RBAC (Role-Based Access Control) implementation
- Multi-company/tenant support
- Email verification and password reset
v1.2.0-beta.2 - Plugin System
- Express.js plugin architecture
- Admin dashboard integration
- Auto-route registration
v1.1.9 - Stable Release
- CRUD generation with Sequelize
- Swagger documentation
- Input validation with Joi
- Unit test generation