master-data-management
v0.1.2
Published
Dynamic Master Table Management module for NestJS with TypeORM
Downloads
165
Maintainers
Readme
Master Table Management
Dynamic, database-driven master table CRUD system for NestJS + TypeORM with comprehensive validation.
🚀 Quick Start
npm install
npm run start:devSwagger API Docs: http://localhost:3000/api
📦 Installation as Package
npm install master-table-managementDependencies: class-validator, class-transformer are required for validation.
Basic Setup (Default Entity)
import { MasterTableModule } from 'master-table-management';
@Module({
imports: [
TypeOrmModule.forRoot({...}),
MasterTableModule.register(),
],
})
export class AppModule {}Custom Entity Setup
import { MasterTableModule } from 'master-table-management';
import { CustomMasterEntity } from './entities/custom-master.entity';
@Module({
imports: [
TypeOrmModule.forRoot({...}),
MasterTableModule.register(CustomMasterEntity),
],
})
export class AppModule {}🗄️ Master Entity Schema
⚠️ REQUIRED FIELDS - DO NOT REMOVE OR RENAME
These fields are mandatory and must exist in your Master entity with exact same names:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | number | ✅ | Primary key (auto-generated) |
| tableName | string | ✅ | Entity table name - Must match TypeORM entity |
| displayColumn | string | ✅ | Display field - Column shown in dropdowns (e.g., "name") |
| isActive | boolean | ✅ | Active status (default: true) |
| createdBy | string | ✅ | User who created the record |
| updatedBy | string | ✅ | User who last updated |
| createdAt | timestamp | ✅ | Creation timestamp (auto-managed) |
| updatedAt | timestamp | ✅ | Last update timestamp (auto-managed) |
🎨 OPTIONAL FIELDS - Can Add or Skip
| Field | Type | Description |
|-------|------|-------------|
| displayName | string | Custom UI name (e.g., "Country" for table master_countries) |
| deletedAt | timestamp | For soft delete support (optional) |
| deletedBy | string | Track who deleted (optional) |
✅ What You CAN Customize
- Table name: Change
@Entity('master_tables')to your preferred table name - Column lengths: Adjust
length: 100to any size you need - Column database names: Change
@Column({ name: 'table_name' })to your convention - Add extra fields: Add any additional columns for your use case
- Nullable fields: Make
displayNameor other optional fields nullable/required as needed
❌ What You CANNOT Change
- Field property names: Must keep
tableName,displayColumn,isActive, etc. (as shown in table above) - Remove required fields: All 8 required fields must exist
- Change data types: Keep id as number, isActive as boolean, etc.
Example - Valid Customization:
@Entity('my_custom_master_config') // ✅ Custom table name
export class CustomMasterEntity {
@PrimaryGeneratedColumn()
id: number; // ✅ Required field - keep as-is
@Column({ name: 'tbl_name', unique: true, length: 200 }) // ✅ Custom DB column name & length
tableName: string; // ✅ Property name must stay "tableName"
@Column({ name: 'disp_col', length: 150 })
displayColumn: string; // ✅ Required field
@Column({ length: 300, nullable: true })
displayName: string; // ✅ Optional - can customize
@Column({ default: true })
isActive: boolean; // ✅ Required field
// ... other required fields ...
@Column({ length: 50, nullable: true })
department: string; // ✅ Add your own custom fields
@Column({ type: 'jsonb', nullable: true })
metadata: any; // ✅ Add any extra columns you need
}📡 API Endpoints
🔹 Entity Management (/master)
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /master/entities | List all registered entities |
| GET | /master | Get all master records |
| GET | /master/:id | Get master record by ID |
| POST | /master | Register new entity |
| PUT | /master/:id | Update entity |
| DELETE | /master/:id | Delete entity |
| PUT | /master/:id/toggle-active | Toggle active status |
🔹 Dynamic Entity Records (/master/:entity)
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /master/:entity/metadata | Get form/grid metadata |
| GET | /master/:entity/options | Get dropdown options |
| GET | /master/:entity/records | Get paginated records |
| GET | /master/:entity/records/:id | Get single record |
| POST | /master/:entity/records | Create record |
| PUT | /master/:entity/records/:id | Update record |
| DELETE | /master/:entity/records/:id | Delete record |
🔹 Export (/master/:entity/export)
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /master/:entity/export/excel | Export to Excel |
| GET | /master/:entity/export/csv | Export to CSV |
🎯 Usage Examples
1. Register a New Entity
POST /master
{
"tableName": "country",
"displayName": "Country",
"displayColumn": "name",
"createdBy": "admin"
}2. Get Entity Metadata (with Validation Rules)
GET /master/country/metadataReturns: Form fields, data types, validation rules, dropdown options
Response includes:
formConfig: Field configurations with validation rulesvalidation: Required, min/max length, patterns, email validation- Frontend can use these rules to implement client-side validation
See VALIDATION.md for complete frontend integration guide.
3. Get Records with Filters
GET /master/country/records?page=1&limit=10&search=India&sortBy=name4. Date Range Filter
GET /master/orders/records?startsAtFrom=2026-01-01&startsAtTo=2026-01-315. Get Dropdown Options
GET /master/country/optionsReturns: [{ id: 1, name: "India" }, ...]
6. Export with Filters
GET /master/country/export/excel?sortBy=name&sortOrder=ASC🔑 Key Features
✅ Database-Driven: Register entities in master_tables - no code changes needed
✅ Auto Relationships: Foreign keys auto-detected, dropdown options auto-generated
✅ Validation: Built-in DTOs with class-validator, validation metadata for frontend
✅ Date Range Filtering: Use fieldFrom and fieldTo for date ranges
✅ Foreign Key Enrichment: APIs return both countryId and countryName
✅ Export: Excel/CSV with metadata preservation
✅ Swagger Docs: Full API documentation included
✅ Custom Entities: Use your own entity via token injection
🛠️ Custom Entity Example
// custom-master.entity.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('my_master_config')
export class CustomMasterEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ name: 'table_name', unique: true, length: 100 })
tableName: string;
@Column({ name: 'display_column', length: 100 })
displayColumn: string;
@Column({ name: 'display_name', length: 200, nullable: true })
displayName: string;
@Column({ name: 'is_active', default: true })
isActive: boolean;
@Column({ name: 'created_by', length: 100 })
createdBy: string;
@Column({ name: 'updated_by', length: 100 })
updatedBy: string;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
}// app.module.ts
MasterTableModule.register(CustomMasterEntity)📊 Response Format
All APIs return:
{
statusCode: 200,
message: "Success message",
data: { ... }
}🗂️ Database Setup
CREATE TABLE master_tables (
id SERIAL PRIMARY KEY,
table_name VARCHAR(100) UNIQUE NOT NULL,
display_name VARCHAR(200),
display_column VARCHAR(100) NOT NULL,
is_active BOOLEAN DEFAULT true,
created_by VARCHAR(100) NOT NULL,
updated_by VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Example: Register entities
INSERT INTO master_tables (table_name, display_name, display_column, created_by, updated_by)
VALUES
('country', 'Country', 'name', 'system', 'system'),
('state', 'State', 'name', 'system', 'system'),
('region', 'Region', 'name', 'system', 'system');📝 Environment Variables
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=yourpassword
DB_DATABASE=yourdb🔗 Links
- Swagger UI: http://localhost:3000/api
- Health Check: http://localhost:3000
⚡ Tips
- displayColumn: Choose a user-friendly field (avoid IDs)
- tableName: Must exactly match TypeORM entity table name
- Date Filtering: Use
dateFromanddateTosuffixes - Relationships: Auto-detected from TypeORM metadata
- Soft Delete: If entity has
deletedAt, uses soft delete
📦 Exports
// Available exports
import {
MasterTableModule,
MasterTableService,
MasterTableRepository,
Master,
MASTER_TABLE_ENTITY_TOKENS,
MESSAGES,
DB_FIELDS,
DATA_TYPES,
} from 'master-table-management';