UNPKG

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
# UCG - Universal CRUD Generator [![npm version](https://badge.fury.io/js/ucg.svg)](https://badge.fury.io/js/ucg) [![npm downloads](https://img.shields.io/npm/dm/ucg.svg)](https://npmjs.org/package/ucg) [![Build Status](https://github.com/jithvar/ucg/workflows/CI%2FCD%20Pipeline/badge.svg)](https://github.com/jithvar/ucg/actions) [![License](https://img.shields.io/badge/License-Free%20Tier-green.svg)](https://github.com/jithvar/ucg/blob/main/LICENSE) [![Node.js](https://img.shields.io/node/v/ucg.svg)](https://nodejs.org) [![Developed by](https://img.shields.io/badge/Developed%20by-Jithvar%20Consultancy-blue.svg)](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** [![npm version](https://badge.fury.io/js/ucg.svg)](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** [![npm version](https://badge.fury.io/js/ucg.svg)](https://badge.fury.io/js/ucg) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Node.js Version](https://img.shields.io/badge/node-%3E%3D16.0.0-brightgreen.svg)](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**: ![npm](https://img.shields.io/npm/dw/ucg) - ๐Ÿ“ˆ **Total Downloads**: ![npm](https://img.shields.io/npm/dt/ucg) - โšก **Bundle Size**: ![npm bundle size](https://img.shields.io/bundlephobia/minzip/ucg) --- **Developed by [Jithvar Consultancy Services](https://jithvar.com)** *Transform your Express.js development workflow. Generate production-ready APIs in seconds.*