JSPM

  • Created
  • Published
  • Downloads 56
  • Score
    100M100P100Q62309F
  • License MIT

Universal Code Generator - Express.js plugin and CLI tool for generating Node.js CRUD APIs with database models, controllers, and admin interface

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

npm version npm downloads Build Status License Node.js Latest Beta Developed by

Express.js CRUD API Generator by Jithvar Consultancy Services - Create complete REST APIs in seconds with database models, controllers, routes, validators, and admin interface. One command to production-ready APIs.

# 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

# 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 + Swagger

Interactive 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 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:

// 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):

ucg generate:crud --model User --orm sequelize
# Generates: Sequelize models with associations, hooks, and scopes

TypeORM:

ucg generate:crud --model User --orm typeorm
# Generates: TypeORM entities with decorators and repositories

Knex.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 dashboard

Automation 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 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:

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:

  1. Check the GitHub Issues
  2. Review the error logs in your console
  3. 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/dbname

Plugin 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 syntax

Database 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 dev

Submitting Pull Requests

  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 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

Stay Updated

  • โญ Star the repo for updates
  • ๐Ÿ‘€ Watch releases for new features
  • ๐ŸŒ Visit: jithvar.com

Performance & Analytics

  • ๐Ÿ“Š Weekly Downloads: npm
  • ๐Ÿ“ˆ Total Downloads: npm
  • โšก Bundle Size: npm 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 use MigrationRunner.runMigrations()
  • Updated runSeeders() to use MigrationRunner.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