ucg
Version:
Universal CRUD Generator - Express.js plugin and CLI tool for generating complete Node.js REST APIs with database models, controllers, routes, validators, and admin interface. Supports PostgreSQL, MySQL, SQLite with Sequelize, TypeORM, and Knex.js. Develo
596 lines (455 loc) โข 18.8 kB
Markdown
# UCG - Universal CRUD Generator
[](https://badge.fury.io/js/ucg)
[](https://npmjs.org/package/ucg)
[](https://github.com/jithvar/ucg/actions)
[](https://github.com/jithvar/ucg/blob/main/LICENSE)
[](https://nodejs.org)
[](https://jithvar.com)
> **Express.js CRUD API Generator** by [Jithvar Consultancy Services](https://jithvar.com) - Create complete REST APIs in seconds with database models, controllers, routes, validators, and admin interface. One command to production-ready APIs.
```bash
# Create a complete REST API in 1 command
npx ucg generate user
# โจ Generates: Model + Controller + Routes + Validator + Swagger Docs + Tests
```
UCG is a powerful **Express.js plugin** and **CLI tool** that generates complete CRUD APIs with:
- ๐ฅ **Database Models** (Sequelize, TypeORM, Knex.js)
- ๐ฏ **REST Controllers** with full CRUD operations
- ๐ฃ๏ธ **Express Routes** with middleware integration
- โ
**Input Validation** (Joi schemas)
- ๐ **Swagger Documentation** (auto-generated)
- ๐งช **Unit Tests** (Jest test suites)
- ๐๏ธ **Admin Interface** (web-based dashboard)
## ๐ฆ Installation
### Global CLI Installation
```bash
npm install -g ucg
ucg --version # Verify installation
ucg --help # See all commands
```
### Project Plugin Installation
```bash
# For new projects
npm init -y
npm install express ucg
# For existing Express projects
npm install ucg
```
### Quick Project Setup
```bash
# Create new project with UCG pre-configured
npx ucg quick-setup --name my-api --db postgres
cd my-api && npm start
```
## ๐ Quick Start
### One-Command Setup
```bash
# Create a complete API in 30 seconds
npx ucg generate user
# โจ Generated: Model + Controller + Routes + Validation + Tests + Swagger
```
### Interactive CLI Setup
```bash
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
```javascript
const express = require('express');
const ucg = require('ucg');
const app = express();
app.use(express.json());
// Mount UCG admin interface and auto-register generated routes
const ucgPlugin = ucg({
mountPath: '/admin',
autoRegisterRoutes: true,
swaggerConfig: {
title: 'My API Documentation',
version: '1.0.0'
}
});
app.use('/admin', ucgPlugin.initialize(app));
app.listen(3000, () => {
console.log('๐ Server: http://localhost:3000');
console.log('๐ Admin: http://localhost:3000/admin');
console.log('๐ Docs: http://localhost:3000/admin/docs');
});
```
## ๐ก 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 mocks
```
**Generated 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:**
```javascript
// 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 user` creates 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):**
```bash
ucg generate:crud --model User --orm sequelize
# Generates: Sequelize models with associations, hooks, and scopes
```
**TypeORM:**
```bash
ucg generate:crud --model User --orm typeorm
# Generates: TypeORM entities with decorators and repositories
```
**Knex.js:**
```bash
ucg generate:crud --model User --orm knex
# Generates: Knex query builders and migrations
```
## ๐๏ธ CLI Commands
### Interactive Mode
```bash
ucg init # Interactive project setup
ucg generate # Interactive model/CRUD generation
ucg start # Launch admin dashboard
```
### Automation Mode
```bash
# 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.
```bash
# 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:
```bash
npm update ucg
```
- **Route Mounting Issues**: Routes not properly integrated into Express app.
**Solution**: Ensure `autoRegisterRoutes: true` is 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:
```javascript
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
```bash
# Start PostgreSQL (macOS with Homebrew)
brew services start postgresql
# Start PostgreSQL (Ubuntu/Debian)
sudo systemctl start postgresql
```
- **Authentication Failed (28P01)**: Incorrect credentials
```bash
# Check PostgreSQL user and password
psql -U your_username -d your_database
```
- **Database Does Not Exist (3D000)**: Database not created
```sql
-- 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:
1. Check the [GitHub Issues](https://github.com/ucg/ucg/issues)
2. Review the error logs in your console
3. Ensure you're using the latest UCG version: `npm update ucg`
## ๐ค Contributingn = ucg({ll -g ucg
# Local installation (for plugin use)
npm install ucg
```
### CLI Usage
```bash
# Initialize UCG in your project
ucg init
# Start the admin interface
ucg start
# Generate CRUD operations
ucg generate:crud --model User
```Express.js plugin and CLI tool for generating Node.js CRUD APIs with database models, controllers, and admin interface**
[](https://badge.fury.io/js/ucg) - Node CRUD Generator
**Express.js plugin and CLI tool for generating Node.js CRUD APIs with database models, controllers, and admin interface**
[](https://badge.fury.io/js/ucg)
[](https://opensource.org/licenses/MIT)
[](https://nodejs.org/)
## ๐ Quick Start
### Installation
```bash
# Global installation (for CLI)
npm install -g ucg
# Local installation (for plugin use)
npm install ucg
```
### Quick Setup (Fastest Way)
```bash
# One-command setup - creates a new project with UCG
npx ucg quick-setup --name my-api
# With custom database
npx ucg quick-setup --name my-api --db postgres
# Navigate to your project and start
cd my-api
npm start
```
### CLI Usage
```bash
# Initialize UCG in your project
ucg init
# Start the admin interface
ucg start
# Generate CRUD operations
ucg generate:crud --model User
```
### Plugin Usage
UCG supports two API patterns for flexibility:
#### Pattern 1: Function Call (Recommended)
```javascript
const express = require('express');
const ucg = require('ucg');
const app = express();
app.use(express.json());
// Initialize UCG plugin
const ucgPlugin = ucg({
mountPath: '/admin',
autoRegisterRoutes: true
});
app.use('/admin', ucgPlugin.initialize(app));
app.listen(3000, () => {
console.log('๐ Server running on http://localhost:3000');
console.log('๐ UCG Admin at http://localhost:3000/admin');
});
```
#### Pattern 2: Class Instantiation
```javascript
const express = require('express');
const { UCGPlugin } = require('ucg');
const app = express();
app.use(express.json());
// Initialize UCG plugin
const ucgPlugin = new UCGPlugin({
mountPath: '/admin',
autoRegisterRoutes: true
});
app.use('/admin', ucgPlugin.initialize(app));
app.listen(3000, () => {
console.log('๐ Server running on http://localhost:3000');
console.log('๐ UCG Admin at http://localhost:3000/admin');
});
```
> **Note**: Both patterns are equivalent and fully supported. Use whichever feels more natural for your project.
## โจ Features
- **๐ฅ Auto Database Config**: Automatically creates database configuration during CRUD generation
- **๐ Auto Route Mounting**: Generated routes are automatically integrated into your app
- **๐ Session Management**: Robust session handling with proper async initialization
- **๐ฅ๏ธ CLI & Web Interface**: Both command-line and web-based management
- **๐๏ธ Multiple ORMs**: Support for Sequelize, TypeORM, and Knex
- **๐ Swagger Documentation**: Auto-generated API documentation
- **โ
Validation**: Input validation with Joi
- **๐ Relational Data**: Complete support for associations and related data
## ๐ Documentation
### Database Configuration
Create a `.env` file in your project root:
```env
DB_HOST=localhost
DB_PORT=5432
DB_NAME=your_database
DB_USER=your_username
DB_PASS=your_password
```
### Available Commands
```bash
ncg init # Initialize NCG in current project
ncg start # Start admin interface
ncg generate:model --table users # Generate model from table
ncg generate:crud --model User # Generate CRUD operations
ncg help # Show all commands
```
### Plugin Options
```javascript
const ncgPlugin = ncg({
mountPath: '/admin', // Mount path for admin interface
autoRegisterRoutes: true, // Auto-mount generated routes
configDir: '.ncg', // Configuration directory
swaggerConfig: {
title: 'My API',
version: '1.0.0',
description: 'API Documentation'
}
});
```
## ๐๏ธ Generated Structure
UCG generates a complete CRUD API structure:
```
src/
โโโ config/
โ โโโ database.js # Auto-generated database configuration
โโโ models/
โ โโโ index.js # Auto-generated models index
โ โโโ User.js # Generated model
โโโ controllers/
โ โโโ userController.js # Generated controller
โโโ services/
โ โโโ userService.js # Generated service layer
โโโ routes/
โ โโโ userRoutes.js # Generated routes
โโโ validators/
โ โโโ userValidator.js # Generated validation
โโโ docs/
โโโ swagger/
โโโ user.swagger.js # Generated API docs
```
## ๐ง Supported Databases
- **PostgreSQL** (Recommended)
- **MySQL/MariaDB**
- **SQLite**
## ๐ง Supported ORMs
- **Sequelize** (Default)
- **TypeORM**
- **Knex.js**
## ๐ API Features
Generated APIs include:
- **GET** `/api/users` - List all users with pagination, filtering, and search
- **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 with validation
- **DELETE** `/api/users/:id` - Delete user
## โ FAQ
### **Q: What's the difference between UCG and other generators?**
**A:** UCG is specifically designed for Express.js with production-ready features like auto-generated tests, Swagger docs, validation, and a web admin interface. Unlike basic scaffolding tools, UCG creates complete, ready-to-deploy APIs.
### **Q: Can I customize the generated code?**
**A:** Yes! UCG supports custom templates, and all generated code is standard JavaScript that you can modify. The `--preview` flag lets you see code before generation.
### **Q: Does UCG work with existing Express apps?**
**A:** Absolutely! UCG can be added to existing projects as a plugin. It auto-detects existing routes and integrates seamlessly without conflicts.
### **Q: What databases are supported?**
**A:** PostgreSQL, MySQL, and SQLite with Sequelize, TypeORM, or Knex.js. MongoDB support is coming soon.
### **Q: Is UCG suitable for production?**
**A:** Yes! Generated code includes validation, error handling, tests, security middleware, and follows Node.js best practices. Many production APIs use UCG-generated code.
### **Q: How do I add authentication to generated APIs?**
**A:** UCG generates standard Express middleware patterns. Add your authentication middleware to the generated routes, or use the admin interface to configure JWT/session authentication.
### **Q: Can I generate APIs for complex database relationships?**
**A:** Yes! UCG automatically detects foreign keys and generates models with proper associations (belongsTo, hasMany, etc.). The admin interface shows relationship diagrams.
## ๐ค Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## ๐ License
UCG is currently **free to use** under our Free Tier License.
**Future Licensing Notice**: [Jithvar Consultancy Services](https://jithvar.com) 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](https://jithvar.com)
## ๐ Support & Links
- **๐ Homepage**: [UCG on GitHub](https://github.com/jithvar/ucg)
- **๐ฆ NPM Package**: [ucg on npmjs](https://www.npmjs.com/package/ucg)
- **๐ Documentation**: Available in admin interface (`/admin/docs`)
- **๐ Issues**: [GitHub Issues](https://github.com/jithvar/ucg/issues)
- **๐ฌ Discussions**: [GitHub Discussions](https://github.com/jithvar/ucg/discussions)
- **๐ Changelog**: [CHANGELOG.md](CHANGELOG.md)
- **๐ License**: [Free Tier License](LICENSE)
- **๐ข Enterprise**: [Jithvar Consultancy Services](https://jithvar.com)
### Stay Updated
- โญ **Star the repo** for updates
- ๐ **Watch releases** for new features
- ๐ **Visit**: [jithvar.com](https://jithvar.com)
### Performance & Analytics
- ๐ **Weekly Downloads**: 
- ๐ **Total Downloads**: 
- โก **Bundle Size**: 
---
**Developed by [Jithvar Consultancy Services](https://jithvar.com)**
*Transform your Express.js development workflow. Generate production-ready APIs in seconds.*