@edsis/generator
v11.7.0
Published
NestJS Code Generator - Generate CRUD modules using native database drivers (pg/mysql2) - NO ORM
Maintainers
Readme
@edsis/generator
A powerful code generator library for NestJS applications that creates production-ready CRUD modules from database metadata.
✨ Feature Availability by Version
| Feature | Version | Status | | ------------------------------------ | -------- | ------------------------------------ | | CRUD Generation | v1.0.0+ | ✅ Core feature | | TypeScript Types | v1.0.0+ | ✅ Full type safety | | Swagger/OpenAPI | v1.0.0+ | ✅ Auto-generated docs | | Advanced Filtering | v2.0.0+ | ✅ 12+ operators | | Pagination | v2.0.0+ | ✅ Offset & cursor | | Sorting | v2.0.0+ | ✅ Multi-column | | RBAC (Role-Based Access Control) | v5.0.0+ | ✅ 92 tests passing | | Audit Trail | v6.0.0+ | ✅ Auto-tracking | | File Upload | v6.0.0+ | ✅ 4 storage providers | | Caching (Redis) | v6.0.0+ | ✅ Smart invalidation | | Export (CSV/Excel) | v6.5.0+ | ✅ Streaming | | Microservices | v7.0.0+ | ✅ TCP/gRPC support | | Schema-Based Structure | v8.0.0+ | ✅ Multi-schema | | Contract-First Pattern | v8.0.0+ | ✅ Shared DTOs | | Remove Command | v9.0.0+ | ✅ Clean deletion | | Smart Code Preservation | v10.0.0+ | ✅ No code loss | | Multi-Architecture | v10.0.0+ | ✅ Standalone/Monorepo/Microservices |
Current Version: 11.0.0 | Test Coverage: 653/815 passing (80%) | Feature Score: 119/100
Latest Changes (v11.0.0):
- ✅ Audit module moved to @edsis/nest (imported via
@edsis/nest/audit) - ✅ Uses subpath imports for tree-shaking (
@edsis/nest/decorators,@edsis/nest/utils) - ✅ Plain SQL architecture with native drivers (pg/mysql2)
- ✅ Updated dependencies: requires @edsis/nest >= 10.1.5
Requirements
Before installing, ensure you have:
- NestJS 11.x or higher
- Node.js 24.0.0 or higher
- npm 11.0.0 or higher
- @edsis/nest 10.1.5 or higher (provides audit module and decorators)
- Database:
- PostgreSQL 18+ OR
- MySQL 8+
⚠️ Warning: This library requires Node.js 24+. Installation on older versions will show warnings and may cause runtime errors.
⚠️ Database Requirements: PostgreSQL 18+ or MySQL 8.0+ is strictly required. The library uses version-specific features like UUID v7 (PostgreSQL) and JSON functions (MySQL 8+). See Database Compatibility Matrix for details.
📦 Dependency: Requires @edsis/nest >= 10.1.5 for audit logging and decorator imports.
Features
✅ No ORM - Uses native database drivers (pg/mysql2) with raw SQL for maximum performance ✅ Multi-Architecture - Standalone, Monorepo, Microservices (fully tested with 0 compilation errors) ✅ Smart Code Preservation - Regenerate without losing custom code ✅ Advanced Filtering - URL-based filters with 12+ operators ✅ Type Safety - Full TypeScript with auto-generated DTOs ✅ Auto Swagger - API documentation generation ✅ RBAC - Complete Role-Based Access Control with 92 passing tests ✅ Audit Trail - Auto-track CREATE, UPDATE, DELETE with @AuditLog (from @edsis/nest/audit) ✅ File Upload - 4 storage providers (Local, S3, GCS, Azure Blob) ✅ Caching - Redis integration with smart invalidation ✅ Export - CSV/Excel streaming for large datasets ✅ Microservices - Gateway + Service controllers with TCP/gRPC support ✅ Subpath Imports - Tree-shaking optimization (@edsis/nest/decorators, @edsis/nest/audit)
Generated Code Uses:
// Authentication (from @edsis/nest)
import { Auth, Public } from '@edsis/nest/decorators';
// Audit logging (from @edsis/nest)
import { AuditLogService } from '@edsis/nest/audit';
// Utilities (from @edsis/nest)
import { toPascalCase, toCamelCase } from '@edsis/nest/utils';Test Coverage: 653/815 passing (80%) | Feature Score: 119/100
Installation
⚠️ Important: This is a development tool and should be installed as a dev dependency:
npm install --save-dev @edsis/generator
npm install @edsis/nest@^11.0.0Other package managers:
# Yarn
yarn add -D @edsis/generator
yarn add @edsis/nest@^11.0.0
# pnpm
pnpm add -D @edsis/generator
pnpm add @edsis/nest@^11.0.0Peer Dependencies
@edsis/generator requires @edsis/nest as a peer dependency:
{
"dependencies": {
"@edsis/nest": "^11.0.0"
},
"devDependencies": {
"@edsis/generator": "^11.0.0"
}
}Why Peer Dependency?
- Version Control - Your project controls the @edsis/nest version
- No Duplicates - Prevents multiple @edsis/nest installations
- Consistent Imports - Generated code uses the same @edsis/nest version
- Smaller Bundle - Single shared dependency instead of nested copies
⚠️ Important Notes:
- Generator is dev dependency only (code generation tool)
- @edsis/nest is production dependency (runtime utilities used by generated code)
- Both must be installed for generator to work
- Generated code imports from
@edsis/nest/*(decorators, audit, utils)
Why Dev Dependency Only?
- Not needed in production - Generates code files during development, not runtime
- Reduces bundle size - Development tools shouldn't bloat production dependencies
- Security - Limits exposure of development tools in production environments
- Best practices - Follows npm/Node.js ecosystem conventions for CLI tools
Note: Installing as a regular dependency (
npm install) will fail with an error. This package is designed to be used during development only.
Usage After Installation
Once installed, use the CLI via npx:
# Initialize configuration
npx nest-generator init
# Generate modules
npx nest-generator generate users.profile
# With features
npx nest-generator generate users.profile \
--features.audit=true \
--features.rbac=true \
--storageProvider=s3CI/CD Environments
Dev dependencies are installed automatically in CI/CD:
npm ci # Installs all dependencies including devDependenciesQuick Start
import { Module } from '@nestjs/common';
import { GeneratorModule } from '@edsis/generator';
@Module({
imports: [GeneratorModule],
})
export class AppModule {}CLI Usage
# Initialize configuration
nest-generator init
nest-generator init --architecture=microservices
# Generate module from metadata (schema.table format)
nest-generator generate entity.entity
nest-generator generate entity.location
# With all features enabled
nest-generator generate entity.entity --all
# With specific features
nest-generator generate entity.location \
--features.audit=true \
--features.rbac=true \
--features.fileUpload=true \
--storageProvider=s3
# For monorepo/microservices: specify target app
nest-generator generate entity.location --app=entity
nest-generator generate orders.order --app=gateway
# Remove generated files (NEW in v2.1.5!)
nest-generator remove entity.location --app=entity
nest-generator remove users.profile --app=user
# Delete module (legacy - for old single-app structure)
nest-generator delete usersRemove Command (NEW!)
The remove command deletes all generated files and updates modules:
# Remove a table from microservices
nest-generator remove entity.location --app=entityWhat it does:
- ✅ Deletes controllers, services, repositories, entities, DTOs
- ✅ Removes from service app (
apps/microservices/entity/src/entity/) - ✅ Removes from gateway app (
apps/microservices/gateway/src/entity/) - ✅ Removes contracts (
libs/contracts/entity/) - ✅ Updates schema modules (removes imports, providers, controllers)
- ✅ Updates
index.tsbarrel exports - ✅ Auto-cleans empty schema directories
- ✅ Removes schema module from app module if empty
Supported architectures:
- Standalone:
nest-generator remove entity.product - Monorepo:
nest-generator remove entity.user --app=user - Microservices:
nest-generator remove entity.location --app=entity
Documentation
Quick Links
- 📖 Complete Documentation Index
- 🚀 5-Minute Quickstart
- 🏗️ Microservices Quickstart
- 🔐 RBAC Complete Guide (1432 lines)
- 📝 Audit Trail Guide
- 📤 File Upload Guide
- ⭐ Feature Scoring (119/100)
- 🎯 Enterprise Quality Guide
- 🗄️ Recommended Database Schemas
Examples
See the examples directory for:
- Basic CRUD setup
- RBAC implementation
- Audit trail configuration
- File upload with S3
- Microservices architecture
- Monorepo setup
Architecture Support
Standalone Application
Single NestJS app with all modules in src/modules/.
Monorepo
Multiple apps sharing common libraries. Each app has its own modules.
Microservices (NEW! Fully Tested)
Distributed services with API gateway pattern:
- Gateway: HTTP REST API with ClientProxy to microservices
- Services: @MessagePattern handlers for TCP/gRPC communication
- Auto-detection: Generates appropriate controllers based on app type
- Transport support: TCP, gRPC, Redis, RabbitMQ, Kafka, NATS
- 0 compilation errors: Fully tested and production-ready
Generated Files
For each table in metadata, generates an organized schema-based directory structure:
{schema-name}/ # Organized by database schema
├── controllers/
│ ├── {table1}.controller.ts # REST or @MessagePattern handlers
│ └── {table2}.controller.ts
├── dto/
│ ├── {table1}/
│ │ ├── create-{table1}.dto.ts # Create DTO with validation
│ │ ├── update-{table1}.dto.ts # Update DTO (partial)
│ │ └── {table1}-filter.dto.ts # Query filters (12+ operators)
│ └── {table2}/
│ └── ...
├── entities/
│ ├── {table1}.entity.ts # Plain TypeScript entity
│ └── {table2}.entity.ts
├── repositories/
│ ├── {table1}.repository.ts # Database operations (raw SQL)
│ └── {table2}.repository.ts
├── services/
│ ├── {table1}.service.ts # Business logic + audit
│ └── {table2}.service.ts
├── {schema-name}.module.ts # Schema module (aggregates all tables)
└── index.ts # Barrel exportsExample for entity schema with tables entity, location, business_entity:
apps/microservices/entity/src/entity/
├── controllers/
│ ├── entity.controller.ts
│ ├── location.controller.ts
│ └── business-entity.controller.ts
├── dto/
│ ├── entity/
│ ├── location/
│ └── business-entity/
├── entities/
│ ├── entity.entity.ts
│ ├── location.entity.ts
│ └── business-entity.entity.ts
├── repositories/
│ ├── entity.repository.ts
│ ├── location.repository.ts
│ └── business-entity.repository.ts
├── services/
│ ├── entity.service.ts
│ ├── location.service.ts
│ └── business-entity.service.ts
├── entity.module.ts # ONE module for entire schema
└── index.tsMicroservices Architecture (NEW!):
Gateway and service apps are separated with shared contracts:
# Service app (entity)
apps/microservices/entity/src/entity/
├── controllers/ # @MessagePattern handlers
├── services/ # Business logic
├── repositories/ # Database access
└── dto/ # Service-specific DTOs (extends contracts)
# Gateway app
apps/microservices/gateway/src/entity/
├── controllers/ # HTTP REST controllers
└── dto/ # Gateway DTOs with Swagger (extends contracts)
# Shared contracts (NO DUPLICATION!)
libs/contracts/entity/
└── dto/
├── entity/
│ ├── create-entity.dto.ts # Base DTOs shared by service & gateway
│ ├── update-entity.dto.ts
│ └── entity-filter.dto.ts
├── location/
└── business-entity/Architecture-specific:
- Standalone/Monorepo: REST controllers with HTTP decorators
- Microservices Gateway: HTTP + ClientProxy to services
- Microservices Service: @MessagePattern handlers for TCP/gRPC
Filter Operators
GET /users?username_like=john&age_gte=18&role_in=admin,userSupported operators:
_eq,_ne- Equality_gt,_gte,_lt,_lte- Comparison_like- Pattern matching (case-insensitive)_in,_nin- Array operations_between- Range queries_null,_nnull- NULL checks
Database Support
- PostgreSQL - Native
pgdriver with UUID v7, JSONB - MySQL - Native
mysql2driver with JSON columns
Metadata Schema
The generator uses PostgreSQL metadata tables to define module structure. These tables must exist in the meta schema:
Core Tables
meta.table - Table/Module Configuration
- Defines NestJS modules to generate
- Controls features (audit, RBAC, caching, export)
- Configures pagination, throttling, permissions
- Primary key:
id(UUID v7) - Unique constraint:
(schema_name, table_name)
meta.column - Column/Field Definitions
- Defines entity properties and DTOs
- Controls validation, display, filtering
- Manages foreign key relationships
- Configures file uploads, search, sorting
- Foreign key:
table_idreferencesmeta.table(id)
meta.generated_files - File Tracking
- Tracks generated files with checksums
- Enables smart code preservation
- Supports regeneration without data loss
- Foreign key:
table_idreferencesmeta.table(id)
Table Structure
-- meta.table (36 columns)
CREATE TABLE meta.table (
id UUID PRIMARY KEY DEFAULT uuidv7(),
schema_name VARCHAR(50) NOT NULL,
table_name VARCHAR(100) NOT NULL,
display_name VARCHAR(255) NOT NULL,
description TEXT,
module_name VARCHAR(100) NOT NULL,
entity_name VARCHAR(100) NOT NULL,
-- Features
has_soft_delete BOOLEAN DEFAULT false,
has_created_by BOOLEAN DEFAULT true,
has_updated_by BOOLEAN DEFAULT true,
enable_export BOOLEAN DEFAULT true,
enable_import BOOLEAN DEFAULT false,
enable_recap BOOLEAN DEFAULT false,
enable_search BOOLEAN DEFAULT false,
-- Caching
cache_enabled BOOLEAN DEFAULT false,
cache_ttl INTEGER DEFAULT 300,
-- Throttling
throttle_enabled BOOLEAN DEFAULT true,
throttle_limit INTEGER DEFAULT 100,
throttle_ttl INTEGER DEFAULT 60,
-- Pagination
default_page_size INTEGER DEFAULT 20,
max_page_size INTEGER DEFAULT 100,
-- Partitioning
is_partitioned BOOLEAN DEFAULT false,
partition_type VARCHAR(50),
partition_key VARCHAR(50),
-- Permissions
permission_config JSONB,
-- UI
icon VARCHAR(50),
color VARCHAR(50),
table_type VARCHAR(50) DEFAULT 'master',
-- Metadata
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
UNIQUE(schema_name, table_name)
);
-- meta.column (42 columns)
CREATE TABLE meta.column (
id UUID PRIMARY KEY DEFAULT uuidv7(),
table_id UUID NOT NULL REFERENCES meta.table(id) ON DELETE CASCADE,
column_name VARCHAR(100) NOT NULL,
data_type VARCHAR(50) NOT NULL,
display_name VARCHAR(255) NOT NULL,
description TEXT,
-- Display Control
display_in_list BOOLEAN DEFAULT true,
display_in_form BOOLEAN DEFAULT true,
display_in_detail BOOLEAN DEFAULT true,
display_in_filter BOOLEAN DEFAULT false,
display_order INTEGER DEFAULT 0,
form_group VARCHAR(100),
-- Validation
is_primary_key BOOLEAN DEFAULT false,
is_nullable BOOLEAN DEFAULT true,
is_unique BOOLEAN DEFAULT false,
is_indexed BOOLEAN DEFAULT false,
is_required BOOLEAN DEFAULT false,
default_value TEXT,
validation_rules JSONB,
-- Filtering
is_filterable BOOLEAN DEFAULT false,
filter_operators TEXT[],
-- Foreign Keys
is_foreign_key BOOLEAN DEFAULT false,
ref_schema VARCHAR(50),
ref_table VARCHAR(100),
ref_column VARCHAR(100),
ref_display_column VARCHAR(100),
on_delete VARCHAR(50),
on_update VARCHAR(50),
-- Input Types
input_type VARCHAR(50) DEFAULT 'text',
select_options JSONB,
conditional_rules JSONB,
placeholder VARCHAR(255),
help_text TEXT,
-- Features
is_searchable BOOLEAN DEFAULT false,
is_sortable BOOLEAN DEFAULT true,
is_file_upload BOOLEAN DEFAULT false,
file_upload_config JSONB,
-- Swagger
swagger_example TEXT,
swagger_hidden BOOLEAN DEFAULT false,
-- Metadata
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
UNIQUE(table_id, column_name)
);Example Usage
-- 1. Define a table/module
INSERT INTO meta.table (
schema_name, table_name, display_name, description,
module_name, entity_name,
enable_export, enable_search, cache_enabled
) VALUES (
'users', 'profile', 'User Profile', 'User profile information',
'profile', 'Profile',
true, true, true
);
-- 2. Define columns/fields
INSERT INTO meta.column (
table_id, column_name, data_type, display_name,
is_required, is_searchable, is_filterable,
validation_rules
) VALUES (
(SELECT id FROM meta.table WHERE schema_name = 'users' AND table_name = 'profile'),
'username', 'varchar', 'Username',
true, true, true,
'{"minLength": 3, "maxLength": 50, "pattern": "^[a-zA-Z0-9_]+$"}'::jsonb
);
-- 3. Generate module
-- nest-generator generate users.profileSetup
Initialize metadata schema using CLI:
npx nest-generator initThis creates:
meta.tabletable with triggersmeta.columntable with foreign keysmeta.generated_filestracking table- Sample data for testing
Custom Code Preservation
// GENERATED_METHOD_START: find-all
async findAll() {
// Auto-generated code
}
// GENERATED_METHOD_END: find-all
// CUSTOM_METHOD_START
async myCustomMethod() {
// Your code - preserved during regeneration
}
// CUSTOM_METHOD_ENDConfiguration
{
"architecture": "standalone",
"database": {
"type": "postgresql",
"host": "localhost",
"port": 5432,
"database": "myapp"
}
}Advanced Features
Swagger/OpenAPI ✅
Auto-generated API documentation with examples and schemas.
Export Functionality ✅
Export to CSV/Excel with streaming for large datasets.
Caching Layer ✅
Redis integration with smart invalidation and configurable TTL.
Audit Trail ✅
Auto-track CREATE, UPDATE, DELETE operations with:
- Change history (old_values → new_values)
- User tracking (created_by, updated_by)
- Timestamp tracking
- Rollback support
RBAC (Role-Based Access Control) ✅
92 passing tests - Production-ready with:
- Permission-based access (
@RequirePermission) - Role-based access (
@RequireRole) - Ownership verification (
@RequireOwnership) - Field-level permissions
- Hierarchical roles with super admin
- Redis caching for performance
- Complete Guide
File Upload ✅
4 storage providers with automatic validation:
- Local: File system storage
- AWS S3: Amazon S3 buckets
- Google Cloud Storage: GCS buckets
- Azure Blob Storage: Azure containers
Microservices Support ✅ NEW!
Full microservices architecture with:
- Schema-based structure: Organized by database schema (e.g.,
entity/,user/) - Contract-First pattern: Shared DTOs in
libs/contracts/to avoid duplication - Auto-detect gateway vs service: Generates appropriate controllers
- TCP/gRPC transport: Message pattern handlers for microservices
- ClientProxy integration: Gateway uses ClientProxy to communicate with services
- Service port from config: Reads host/port from
config/generator/microservices.config.json - Remove command: Clean deletion of generated files with module updates
- Quickstart Guide
Recent Bug Fixes (v2.1.5):
- ✅ Fixed DTO import aliases (no more
EntityDto as CreateEntityDto) - ✅ Swagger only for gateway (not generated for TCP microservices)
- ✅ AuditModule auto-imports when audit enabled
- ✅ Service ports from config (no more hardcoded 3001)
- ✅ Gateway
index.tsonly exports controllers and DTOs (not entities/services) - ✅ Dynamic root module detection (
*-service.module.ts)
Recent Changes
v3.0.2 (November 2025)
Bug Fixes:
- 🔧 Fixed remove command cleanup logic for gateway modules
- 🧹 Properly removes imports and updates controllers array
- ✨ New updateBarrelExports method for index.ts cleanup
- 📦 removeFromArray helper for clean array item removal
- 🗑️ Auto-cleanup empty schemas and update app module
v3.0.1 (November 2025)
Improvements:
- 📚 Added version synchronization checklist for publishing
- 🔧 Improved version-bump.sh script with confirmation prompts
- 📖 Documentation updates for version consistency
v3.0.0 (November 2025) - BREAKING CHANGES
Major Changes:
- 🚨 BREAKING: Schema-based directory structure replaces per-table structure
- 🚨 BREAKING: Contract-First pattern requires
libs/contracts/directory - 🎉 NEW:
removecommand for deleting generated files - ⚙️ Service config from
config/generator/*.config.json
Bug Fixes:
- Fixed DTO import aliases in service DTOs
- Swagger generation only for gateway apps
- AuditModule auto-import when audit feature enabled
- Service ports read from config instead of hardcoded
- Gateway barrel exports (index.ts) exclude non-existent files
- Warning removal for missing
app.module.ts
Test Coverage: 579/585 passing (99%) | Feature Score: 119/100
License
MIT
Author
Ojie Permana
Support
- Issues: GitHub Issues
- Repository: GitHub
