JSPM

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

Express.js plugin and CLI tool for generating Node.js CRUD APIs with comprehensive Swagger documentation, RBAC authentication system, and enterprise-grade features

Package Exports

    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

    ๐Ÿš€ Plug-and-Play Express.js API Generator - Generate complete authentication systems with RBAC, multi-company support, and Swagger documentation in seconds!

    n    availableRoutes: {
      dashboard: '/ucg',
      documentation: '/ucg/docs',
      health: '/health',
      auth: '/api/auth/*',
      users: '/api/users/*',
      roles: '/api/roles/*',
      permissions: '/api/permissions/*'
    }on npm downloads

    โšก Quick Start (5 Minutes to Full API)

    Step 1: Create New Project

    mkdir my-api-project
    cd my-api-project
    npm init -y

    Step 2: Install UCG

    npm install ucg@beta

    Step 3: Install Dependencies

    npm install express sequelize pg bcryptjs jsonwebtoken dotenv express-rate-limit express-validator helmet cors compression morgan

    Step 4: Create Environment File

    Create .env file with your database configuration:

    # Database Configuration
    DB_NAME=your_database_name
    DB_USER=postgres
    DB_PASS=your_password
    DB_HOST=localhost
    DB_PORT=5432
    DB_DIALECT=postgres
    
    # JWT Secrets (IMPORTANT: Use strong secrets in production!)
    JWT_SECRET=your-super-secret-jwt-key-here-change-in-production-at-least-32-chars
    JWT_REFRESH_SECRET=your-refresh-secret-key-here-change-in-production-at-least-32-chars
    JWT_ACCESS_EXPIRES_IN=15m
    JWT_REFRESH_EXPIRES_IN=7d
    
    # Server Configuration
    NODE_ENV=development
    PORT=3000
    
    # Email Configuration (Optional - for password reset/verification)
    SMTP_HOST=smtp.gmail.com
    SMTP_PORT=587
    SMTP_USER=your-email@gmail.com
    SMTP_PASS=your-16-digit-app-password
    SMTP_FROM=your-email@gmail.com

    Step 5: Generate Authentication System

    npx ucg generate:auth --features rbac,swagger,company -o src --skip-deps

    Step 6: Create Main App File

    Create app.js:

    const express = require('express');
    const cors = require('cors');
    const helmet = require('helmet');
    const compression = require('compression');
    const morgan = require('morgan');
    require('dotenv').config();
    
    const app = express();
    
    // Security middleware
    app.use(helmet({
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
          styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
          fontSrc: ["'self'", "https://fonts.gstatic.com"],
          scriptSrc: ["'self'"],
          imgSrc: ["'self'", "data:", "https:"],
        },
      },
    }));
    
    app.use(cors());
    app.use(compression());
    app.use(morgan('combined'));
    
    // Body parsing middleware
    app.use(express.json({ limit: '10mb' }));
    app.use(express.urlencoded({ extended: true, limit: '10mb' }));
    
    // Health check
    app.get('/health', (req, res) => {
      res.json({ 
        status: 'OK', 
        timestamp: new Date().toISOString(),
        uptime: process.uptime()
      });
    });
    
    // Optional: Manual swagger setup (UCG provides automatic documentation at /ucg/docs)
    // The UCG plugin automatically generates comprehensive Swagger documentation
    // If you want additional custom swagger configuration, you can add it here:
    /*
    const swaggerOptions = {
      definition: {
        openapi: '3.0.0',
        info: {
          title: 'Custom API Extension',
          version: '1.0.0',
          description: 'Additional custom endpoints',
        },
        servers: [
          { url: `http://localhost:${process.env.PORT || 3000}` }
        ],
      },
      apis: ['./src/routes/custom/*.js'], // Your custom routes
    };
    
    const customSwaggerSpec = swaggerJsdoc(swaggerOptions);
    app.use('/api/docs/custom', swaggerUi.serve, swaggerUi.setup(customSwaggerSpec));
    */
    
    // UCG Plugin - Plug and Play CRUD Generator
    const ucg = require('ucg');
    
    // Mount UCG dashboard and management interface
    app.use('/ucg', ucg({
      autoRegisterRoutes: true,
      swaggerConfig: {
        title: 'Generated API Documentation',
        version: '1.0.0',
        description: 'Auto-generated CRUD API with authentication'
      }
    }));
    
    // Auto-discover and mount generated API routes
    const ucgAutoRoutes = ucg.autoDiscoverRoutes('./src/routes');
    app.use('/api', ucgAutoRoutes);
    console.log('โœ… UCG auto-discovery enabled for API routes');
    
    // Welcome route
    app.get('/', (req, res) => {
      res.json({
        message: '๐Ÿš€ UCG Generated API Server',
        version: '1.0.0',
        dashboard: `http://localhost:${process.env.PORT || 3000}/ucg`,
        documentation: `http://localhost:${process.env.PORT || 3000}/ucg/docs`,
        endpoints: {
          auth: '/api/auth/*',
          users: '/api/users/*',
          roles: '/api/roles/*',
          permissions: '/api/permissions/*',
          companies: '/api/companies/*',
        },
        generated_by: 'UCG - Universal CRUD Generator'
      });
    });
    
    // Error handling middleware
    app.use((err, req, res, next) => {
      console.error('Error:', err);
      
      // Handle specific error types
      if (err.name === 'ValidationError') {
        return res.status(400).json({
          success: false,
          message: 'Validation Error',
          errors: err.errors || err.message
        });
      }
      
      if (err.name === 'UnauthorizedError') {
        return res.status(401).json({
          success: false,
          message: 'Unauthorized'
        });
      }
    
      // Default error response
      res.status(err.statusCode || 500).json({
        success: false,
        message: err.message || 'Internal Server Error',
        ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
      });
    });
    
    // 404 handler
    app.use((req, res) => {
      res.status(404).json({
        success: false,
        message: 'Route not found',
        availableRoutes: {
          documentation: '/ucg/docs',
          health: '/health',
          auth: '/api/auth/*',
          users: '/api/users/*',
          roles: '/api/roles/*',
          permissions: '/api/permissions/*'
        }
      });
    });
    
    const PORT = process.env.PORT || 3000;
    
    app.listen(PORT, () => {
      console.log('๐Ÿš€ Server started successfully!');
      console.log(`๐Ÿ“ก Server running on port ${PORT}`);
      console.log(`๐ŸŽ›๏ธ  UCG Dashboard: http://localhost:${PORT}/ucg`);
      console.log(`๐Ÿ“š API Documentation: http://localhost:${PORT}/ucg/docs`);
      console.log(`๐Ÿฅ Health Check: http://localhost:${PORT}/health`);
      console.log(`๐Ÿ”ง Generated by: UCG - Universal CRUD Generator`);
    });
    
    module.exports = app;

    Step 7: Add Start Script

    Add to your package.json:

    {
      "scripts": {
        "start": "node app.js",
        "dev": "nodemon app.js"
      }
    }

    Step 8: Run Migrations

    npx ucg migrate

    Step 9: Seed Demo Data (Optional)

    npx ucg seed

    Step 10: Start Your API

    npm start

    ๐ŸŽ‰ Done! Your API is now running at http://localhost:3000

    ๐Ÿ“š What You Get

    ๐ŸŽฏ Complete Authentication System (Ready in 5 Minutes!)

    UCG generates a production-ready authentication API with all these features:

    โœ… What's Generated Automatically

    • ๐Ÿ” JWT Authentication (Access + Refresh tokens)
    • ๐Ÿ‘ฅ User Management (Registration, login, profile management)
    • ๐Ÿ›ก๏ธ Role-Based Access Control (RBAC) (Roles, permissions, groups)
    • ๐Ÿข Multi-Company/Tenant Support (Optional)
    • ๐Ÿ“ง Email Integration (Password reset, email verification)
    • ๐Ÿ“Š Swagger Documentation (Interactive API testing)
    • ๐Ÿ”’ Security Middleware (Rate limiting, validation, CORS)
    • ๐Ÿ“ Complete Database Schema (10 tables with relationships)
    • ๐Ÿงช Demo Data (Test users, roles, permissions)

    ๐Ÿ”— Generated API Endpoints (47 total)

    ๐Ÿ” Authentication (8 endpoints)

    POST   /api/auth/register           # Register new user
    POST   /api/auth/login              # User login
    POST   /api/auth/refresh            # Refresh JWT token
    GET    /api/auth/me                 # Get current user profile
    PUT    /api/auth/change-password    # Change user password
    POST   /api/auth/forgot-password    # Request password reset (email)
    POST   /api/auth/reset-password     # Reset password with token
    POST   /api/auth/logout             # Logout user

    ๐Ÿ‘ฅ Users Management (6 endpoints)

    GET    /api/users                   # List all users (with pagination)
    POST   /api/users                   # Create new user
    GET    /api/users/:id               # Get user by ID
    PUT    /api/users/:id               # Update user
    DELETE /api/users/:id               # Delete user
    POST   /api/users/:id/assign-roles  # Assign roles to user

    ๐Ÿ›ก๏ธ Roles & Permissions (21 endpoints)

    # Roles
    GET    /api/roles                   # List all roles
    POST   /api/roles                   # Create new role
    GET    /api/roles/:id               # Get role details
    PUT    /api/roles/:id               # Update role
    DELETE /api/roles/:id               # Delete role
    POST   /api/roles/:id/permissions   # Assign permissions to role
    
    # Permissions
    GET    /api/permissions             # List all permissions
    POST   /api/permissions             # Create permission
    GET    /api/permissions/:id         # Get permission details
    PUT    /api/permissions/:id         # Update permission
    DELETE /api/permissions/:id         # Delete permission
    POST   /api/permissions/check       # Check user permissions
    
    # Permission Groups
    GET    /api/permission-groups       # List permission groups
    POST   /api/permission-groups       # Create permission group
    GET    /api/permission-groups/:id   # Get group details
    PUT    /api/permission-groups/:id   # Update group
    DELETE /api/permission-groups/:id   # Delete group

    ๐Ÿข Multi-Company Support (12 endpoints)

    GET    /api/companies               # List companies
    POST   /api/companies               # Create company
    GET    /api/companies/:id           # Get company details
    PUT    /api/companies/:id           # Update company
    DELETE /api/companies/:id           # Delete company
    GET    /api/companies/:id/users     # Get company users
    POST   /api/companies/:id/users     # Add user to company
    DELETE /api/companies/:id/users/:userId # Remove user from company
    PUT    /api/companies/:id/settings  # Update company settings
    GET    /api/companies/:id/roles     # Get company roles
    POST   /api/companies/:id/roles     # Create company role
    GET    /api/companies/:id/stats     # Company statistics

    ๐Ÿงช Testing Your API

    1. Access Swagger Documentation

    Open http://localhost:3000/ucg/docs for interactive API testing with:

    • ๐Ÿ” Complete endpoint documentation
    • ๐Ÿงช Test any endpoint directly from browser
    • ๐Ÿ” JWT authentication testing
    • ๐Ÿ“ Request/response examples

    2. Test Authentication Flow

    # 1. Register a new user
    curl -X POST http://localhost:3000/api/auth/register \
      -H "Content-Type: application/json" \
      -d '{
        "firstName": "John",
        "lastName": "Doe", 
        "email": "john@example.com",
        "password": "SecurePass123!"
      }'
    
    # 2. Login to get JWT token
    curl -X POST http://localhost:3000/api/auth/login \
      -H "Content-Type: application/json" \
      -d '{
        "email": "john@example.com",
        "password": "SecurePass123!"
      }'
    
    # 3. Use JWT token for protected endpoints
    curl -X GET http://localhost:3000/api/users \
      -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE"

    3. Demo Data (After running migrations & seeding)

    The system comes with pre-configured demo data:

    # Demo login credentials (after running: npx ucg seed)
    Email: admin@company.com
    Password: TempPass123!
    
    # Or using curl:
    curl -X POST http://localhost:3000/api/auth/login \
      -H "Content-Type: application/json" \
      -d '{
        "email": "admin@company.com",
        "password": "TempPass123!"
      }'

    โš™๏ธ Advanced Configuration

    CLI Commands

    # Generate authentication system with specific features
    npx ucg generate:auth --features rbac,company,swagger,email
    
    # Generate basic CRUD (coming soon)
    npx ucg generate:crud --model Product --table products
    
    # Run database migrations
    npx ucg migrate
    
    # Seed demo data
    npx ucg seed
    
    # Check UCG version
    npx ucg --version

    Available Features

    • rbac - Role-based access control
    • company - Multi-company/tenant support
    • swagger - API documentation
    • email - Email integration (password reset, verification)

    ๐Ÿ—„๏ธ Database Setup

    Prerequisites

    You need a PostgreSQL database. Here's how to set it up:

    Option 1: Local PostgreSQL

    # Install PostgreSQL (macOS)
    brew install postgresql
    brew services start postgresql
    
    # Create database
    createdb my_api_database
    
    # Create user (optional)
    psql -c "CREATE USER myuser WITH PASSWORD 'mypassword';"
    psql -c "GRANT ALL PRIVILEGES ON DATABASE my_api_database TO myuser;"

    Option 2: Docker PostgreSQL

    # Run PostgreSQL in Docker
    docker run --name postgres-ucg \
      -e POSTGRES_DB=my_api_database \
      -e POSTGRES_USER=myuser \
      -e POSTGRES_PASSWORD=mypassword \
      -p 5432:5432 \
      -d postgres:13

    Option 3: Cloud Database

    Use any cloud PostgreSQL service:

    • Heroku Postgres (free tier available)
    • AWS RDS
    • Google Cloud SQL
    • DigitalOcean Managed Database

    Update Your .env File

    After setting up your database, update your .env:

    DB_NAME=my_api_database
    DB_USER=myuser
    DB_PASS=mypassword
    DB_HOST=localhost
    DB_PORT=5432
    DB_DIALECT=postgres

    ๐Ÿ“ง Email Configuration (Optional)

    1. Enable 2-Factor Authentication in your Google Account
    2. Go to Google Account โ†’ Security โ†’ App Passwords
    3. Generate an App Password for "Mail"
    4. Use the 16-digit code in your .env:
    SMTP_HOST=smtp.gmail.com
    SMTP_PORT=587
    SMTP_USER=your.email@gmail.com
    SMTP_PASS=your-16-digit-app-password
    SMTP_FROM=your.email@gmail.com

    Other Email Providers

    # Outlook/Hotmail
    SMTP_HOST=smtp-mail.outlook.com
    SMTP_PORT=587
    
    # Yahoo
    SMTP_HOST=smtp.mail.yahoo.com
    SMTP_PORT=587
    
    # Custom SMTP
    SMTP_HOST=your-smtp-server.com
    SMTP_PORT=587

    ๐Ÿ“ Project Structure

    After running UCG, your project will have this structure:

    my-api-project/
    โ”œโ”€โ”€ app.js                          # Main application file
    โ”œโ”€โ”€ package.json                    # Dependencies and scripts
    โ”œโ”€โ”€ .env                           # Environment variables
    โ”‚
    โ”œโ”€โ”€ src/
    โ”‚   โ”œโ”€โ”€ controllers/               # API Controllers
    โ”‚   โ”‚   โ”œโ”€โ”€ authController.js      # Authentication logic
    โ”‚   โ”‚   โ”œโ”€โ”€ userController.js      # User management
    โ”‚   โ”‚   โ”œโ”€โ”€ roleController.js      # Role management
    โ”‚   โ”‚   โ””โ”€โ”€ permissionController.js # Permission management
    โ”‚   โ”‚
    โ”‚   โ”œโ”€โ”€ routes/                    # Express Routes
    โ”‚   โ”‚   โ”œโ”€โ”€ authRoutes.js          # Auth endpoints
    โ”‚   โ”‚   โ”œโ”€โ”€ userRoutes.js          # User endpoints
    โ”‚   โ”‚   โ”œโ”€โ”€ roleRoutes.js          # Role endpoints
    โ”‚   โ”‚   โ””โ”€โ”€ permissionRoutes.js    # Permission endpoints
    โ”‚   โ”‚
    โ”‚   โ”œโ”€โ”€ middleware/                # Custom Middleware
    โ”‚   โ”‚   โ”œโ”€โ”€ auth-middleware.js     # JWT verification
    โ”‚   โ”‚   โ”œโ”€โ”€ rbac-middleware.js     # Role-based access control
    โ”‚   โ”‚   โ””โ”€โ”€ validation-middleware.js # Request validation
    โ”‚   โ”‚
    โ”‚   โ”œโ”€โ”€ models/                    # Database Models
    โ”‚   โ”‚   โ”œโ”€โ”€ index.js               # Sequelize setup
    โ”‚   โ”‚   โ”œโ”€โ”€ User.js                # User model
    โ”‚   โ”‚   โ”œโ”€โ”€ Role.js                # Role model
    โ”‚   โ”‚   โ””โ”€โ”€ Permission.js          # Permission model
    โ”‚   โ”‚
    โ”‚   โ”œโ”€โ”€ utils/                     # Utility Functions
    โ”‚   โ”‚   โ”œโ”€โ”€ app-error.js           # Custom error handling
    โ”‚   โ”‚   โ”œโ”€โ”€ async-handler.js       # Async error wrapper
    โ”‚   โ”‚   โ”œโ”€โ”€ response-formatter.js  # API response formatting
    โ”‚   โ”‚   โ””โ”€โ”€ token-utils.js         # JWT utilities
    โ”‚   โ”‚
    โ”‚   โ”œโ”€โ”€ validators/                # Input Validation
    โ”‚   โ”‚   โ”œโ”€โ”€ authValidators.js      # Auth validation rules
    โ”‚   โ”‚   โ””โ”€โ”€ userValidators.js      # User validation rules
    โ”‚   โ”‚
    โ”‚   โ””โ”€โ”€ database/
    โ”‚       โ”œโ”€โ”€ migrations/            # Database migrations
    โ”‚       โ””โ”€โ”€ seeders/               # Demo data seeders
    โ”‚
    โ””โ”€โ”€ logs/                          # Application logs (auto-created)

    ๐Ÿš€ Deployment

    Environment Variables for Production

    NODE_ENV=production
    PORT=3000
    DB_NAME=your_production_db
    DB_USER=your_production_user
    DB_PASS=your_production_password
    DB_HOST=your_production_host
    JWT_SECRET=your-super-secure-production-secret-at-least-64-characters-long
    JWT_REFRESH_SECRET=your-refresh-secret-at-least-64-characters-long

    Deploy to Heroku

    # Install Heroku CLI, then:
    heroku create your-api-name
    heroku addons:create heroku-postgresql:hobby-dev
    heroku config:set NODE_ENV=production
    heroku config:set JWT_SECRET=your-production-secret
    heroku config:set JWT_REFRESH_SECRET=your-refresh-secret
    
    # Deploy
    git add .
    git commit -m "Initial commit"
    git push heroku main
    
    # Run migrations on Heroku
    heroku run npx ucg migrate
    heroku run npx ucg seed

    Deploy to DigitalOcean App Platform

    1. Connect your GitHub repository
    2. Set environment variables in the control panel
    3. App Platform will automatically deploy

    Deploy with Docker

    FROM node:18-alpine
    WORKDIR /app
    COPY package*.json ./
    RUN npm ci --only=production
    COPY . .
    EXPOSE 3000
    CMD ["npm", "start"]

    โ— Troubleshooting

    Common Issues & Solutions

    "Cannot find module" errors

    # Make sure you installed all dependencies
    npm install express sequelize pg bcryptjs jsonwebtoken dotenv express-rate-limit express-validator helmet cors compression morgan
    
    # Regenerate auth system if needed
    npx ucg generate:auth --features rbac,swagger -o src --skip-deps

    Database connection errors

    # Check your .env file has correct database credentials
    # Make sure PostgreSQL is running
    # Test connection:
    psql -h localhost -U your_username -d your_database_name
    
    # Run migrations:
    npx ucg migrate

    Migration errors ("table already exists")

    # Reset database (WARNING: This deletes all data)
    dropdb your_database_name && createdb your_database_name
    npx ucg migrate
    npx ucg seed

    Email not working

    # For Gmail, use App Password, not regular password
    # Check SMTP settings in .env file
    # Make sure 2FA is enabled on Gmail account

    Port already in use

    # Kill process on port 3000
    lsof -ti:3000 | xargs kill -9
    
    # Or use different port
    PORT=3001 npm start

    ๐Ÿ”ง Customization

    Adding Custom Routes

    Add your custom routes to app.js:

    // Add after UCG routes
    app.use('/api/custom', require('./src/routes/customRoutes'));

    Custom Middleware

    // Add custom middleware before routes
    app.use('/api', (req, res, next) => {
      console.log(`${req.method} ${req.path} - ${new Date().toISOString()}`);
      next();
    });

    Environment-Specific Configuration

    // In app.js
    if (process.env.NODE_ENV === 'development') {
      app.use(morgan('dev'));
    } else {
      app.use(morgan('combined'));
    }

    ๐ŸŽ“ Learning Resources

    Key Concepts to Understand

    • JWT Authentication: Access & refresh tokens
    • RBAC: Role-based access control
    • Express.js: Node.js web framework
    • Sequelize: SQL ORM for Node.js
    • Swagger: API documentation standard
    1. Explore UCG Dashboard: http://localhost:3000/ucg
    2. Explore Swagger Docs: http://localhost:3000/ucg/docs
    3. Test all endpoints using the interactive documentation
    4. Customize the generated code to fit your needs
    5. Add your own business logic to controllers
    6. Deploy to production using Heroku, DigitalOcean, or AWS

    ๐Ÿ†˜ Support & Community

    ๐ŸŽ‰ Success Stories

    "UCG saved us weeks of development time. We had a complete authentication API running in 10 minutes!" - Development Team Lead

    "The generated Swagger documentation is perfect for our frontend team." - Full Stack Developer

    "Finally, an API generator that just works out of the box!" - Startup Founder

    ๐Ÿ“Š What Makes UCG Different

    Feature UCG Other Generators
    Setup Time 5 minutes Hours/Days
    Production Ready โœ… Yes โŒ Needs work
    Authentication โœ… Complete system โŒ Basic only
    Documentation โœ… Auto-generated โŒ Manual
    RBAC โœ… Built-in โŒ Custom code needed
    Multi-tenant โœ… Supported โŒ Not included
    Email Integration โœ… Ready to use โŒ Manual setup

    ๐Ÿ“„ License

    MIT License - see LICENSE file for details.


    ๐Ÿš€ Ready to Build Your API?

    # Start your next project now:
    mkdir my-awesome-api
    cd my-awesome-api
    npm init -y
    npm install ucg@beta
    # Follow the quick start guide above!

    Made with โค๏ธ by Jithvar Consultancy Services

    UCG - From zero to production-ready APIs in 5 minutes! ๐ŸŽ‰