echo-crud-factory
v1.0.1
Published
Production-grade CLI code generator for Node.js backend modules with strict conventions and mandatory Swagger documentation
Maintainers
Readme
Echo CRUD Factory
Production-grade CLI code generator for Node.js backend modules with strict conventions and mandatory Swagger documentation
Overview
Echo CRUD Factory is an enterprise-ready CLI tool that generates consistent, opinionated, production-ready CRUD modules for Node.js backends. It enforces strict naming conventions, provides mandatory Swagger documentation, and supports multiple ORMs and databases.
Features
✅ Schema-Driven Generation - Single JSON schema as source of truth
✅ Strict Naming Conventions - Enforced snake_case, kebab-case, PascalCase
✅ Mandatory Swagger/OpenAPI 3.x - Complete API documentation for every endpoint
✅ Multi-ORM Support - Sequelize, TypeORM, Prisma
✅ Multi-Database Support - MySQL, PostgreSQL, SQLite, MariaDB, MSSQL
✅ Yup Validation - 1:1 mapping to Yup API with strict validation
✅ Express-First - Framework-agnostic but optimized for Express
✅ Deterministic Output - Same input always produces same output
✅ Rollback on Failure - Automatic cleanup if generation fails
✅ Dry-Run Mode - Preview files before writing
Requirements
- Node.js: v22.0.0 or higher
- npm: v9.0.0 or higher
Installation
Local Installation (Recommended)
Install as a dev dependency in your project:
npm install --save-dev echo-crud-factoryImportant: With local installation, you must use npx prefix for all commands:
npx echo-crud-factory generate --entity=User --fields=./schema.jsonQuick Start
1. Initialize Configuration
npx echo-crud-factory init --interactiveThis creates a .echocrudfactoryrc file with your preferences:
{
"orm": "sequelize",
"database": "mysql",
"apiCase": "snake_case",
"dbCase": "snake_case",
"withService": true,
"withRepository": false,
"withSoftDelete": true,
"withPagination": true,
"withTimestamps": true,
"swaggerEnabled": true
}2. Create Schema File
Create user-schema.json:
[
{
"column_name": "id",
"type": "primary"
},
{
"column_name": "first_name",
"type": "string",
"mandatory": true,
"validations": ["min:3", "max:50", "regex:/^[a-zA-Z\\s]+$/"]
},
{
"column_name": "email",
"type": "string",
"mandatory": true,
"unique": true,
"validations": ["email"]
},
{
"column_name": "age",
"type": "integer",
"validations": ["min:18", "max:120"]
},
{
"column_name": "status",
"type": "enum",
"enum_values": ["active", "inactive", "suspended"],
"default_value": "active"
}
]3. Generate Module
npx echo-crud-factory generate --entity=User --fields=./user-schema.json4. Generated Files
src/
├── controllers/
│ └── user.controller.js
├── models/
│ └── user.model.js
├── routes/
│ └── user.routes.js
├── validators/
│ └── user.validator.js
└── swagger/
└── user.swagger.js
db/
└── migrations/
└── 20260113185550-create-users.jsCLI Commands
generate (alias: g)
Generate CRUD module for an entity.
npx echo-crud-factory generate --entity=User --fields=./schema.json [options]Options:
--entity <name>- Entity name in PascalCase (required)--table <name>- Table name in snake_case (optional, auto-generated)--fields <path>- Path to JSON schema file (required)--dry-run- Preview files without writing--force- Overwrite existing files--verbose- Enable verbose logging
Examples:
# Basic generation
npx echo-crud-factory generate --entity=User --fields=./user-schema.json
# Custom table name
npx echo-crud-factory generate --entity=User --table=app_users --fields=./schema.json
# Dry run (preview only)
npx echo-crud-factory generate --entity=Product --fields=./schema.json --dry-run
# Force overwrite
npx echo-crud-factory generate --entity=Order --fields=./schema.json --forceinit
Initialize Echo CRUD Factory configuration.
npx echo-crud-factory init [--interactive]Options:
--interactive- Interactive configuration setup
check
Validate schema file.
npx echo-crud-factory check --fields=./schema.jsondoctor
Check system dependencies and configuration.
npx echo-crud-factory doctorconfig
View or update configuration.
# Show current configuration
npx echo-crud-factory config --show
# Update configuration
npx echo-crud-factory config --set orm=typeorm
npx echo-crud-factory config --set withService=falseSchema File Specification
Column Definition
{
"column_name": string, // snake_case (required)
"type": ColumnType, // (required)
"mandatory": boolean, // (optional)
"unique": boolean, // (optional)
"default_value": any, // (optional)
"validations": string[], // (optional)
"enum_values": string[], // (required for enum type)
"length": number, // (optional, for string)
"precision": number, // (optional, for float)
"scale": number, // (optional, for float)
"foreign_key": { // (optional)
"table": string,
"column": string,
"on_delete": string,
"on_update": string
},
"index": boolean // (optional)
}Supported Column Types
primary- Primary key (BIGINT, auto-increment)string- VARCHARtext- TEXTinteger- INTEGERbigint- BIGINTfloat- FLOAT/DECIMALboolean- BOOLEANdate- DATE/DATETIMEenum- ENUM (requires enum_values)json- JSON
Validation Rules
All validation rules map 1:1 to Yup API:
required- Field is requiredemail- Valid email formaturl- Valid URL formatuuid- Valid UUID formatmin:N- Minimum length/valuemax:N- Maximum length/valuelength:N- Exact lengthmatches:/pattern/orregex:/pattern/- Regex patternoneOf:val1,val2- One of specified valuespositive- Positive numbernegative- Negative numberinteger- Integer numberlessThan:N- Less than valuemoreThan:N- More than value
Example:
{
"column_name": "username",
"type": "string",
"mandatory": true,
"validations": [
"min:3",
"max:20",
"regex:/^[a-zA-Z0-9_]+$/"
]
}Naming Conventions (Strictly Enforced)
| Layer | Convention | Example |
|-------|------------|---------|
| Entity (input) | PascalCase | User, ProductCategory |
| API request/response | snake_case | first_name, created_at |
| DTOs | snake_case | user_id, order_total |
| Yup schemas | snake_case | email, phone_number |
| Database columns | snake_case | first_name, created_at |
| Database tables | snake_case (plural) | users, product_categories |
| Files & folders | kebab-case | user.controller.js, product-category.routes.js |
Any violation will fail generation with a descriptive error.
Generated Code Structure
Controller
Express-compatible controllers with:
- Async/await
- Centralized error handling
- snake_case DTOs
- CRUD methods:
create,list,get_by_id,update,delete/soft_delete
Model
ORM models with:
- snake_case columns
- Primary key:
id(BIGINT) - Timestamps:
created_at,updated_at,deleted_at - Proper data types and constraints
Routes
RESTful endpoints:
POST /api/users- CreateGET /api/users- List with paginationGET /api/users/:id- Get by IDPUT /api/users/:id- UpdateDELETE /api/users/:id- DeletePOST /api/users/:id/restore- Restore (if soft delete enabled)
Validators
Yup validation schemas:
- Create schema (mandatory fields required)
- Update schema (all fields optional)
- Query schema (for filtering)
- Pagination schema
Swagger
OpenAPI 3.x documentation:
- Complete request/response schemas
- All parameters documented
- Success and error responses
- Tags for organization
Migrations
Database migrations:
- Timestamp-based naming
- Up/down migrations
- Indexes and constraints
- Foreign keys
Configuration Options
.echocrudfactoryrc
{
"orm": "sequelize", // sequelize | typeorm | prisma
"database": "mysql", // mysql | postgresql | sqlite | mariadb | mssql
"apiCase": "snake_case", // Always snake_case (enforced)
"dbCase": "snake_case", // Always snake_case (enforced)
"withService": true, // Generate service layer
"withRepository": false, // Generate repository layer
"withSoftDelete": true, // Enable soft delete
"withPagination": true, // Enable pagination
"withTimestamps": true, // Add created_at, updated_at
"swaggerEnabled": true // Always true (mandatory)
}Supported ORMs
Sequelize (Default)
npm install sequelize mysql2TypeORM
npm install typeorm reflect-metadata mysql2Prisma
npm install @prisma/client
npm install -D prismaIntegration Example
Express App Integration
import express from 'express';
import userRoutes from './routes/user.routes.js';
import swaggerJsdoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
const app = express();
app.use(express.json());
// Routes
app.use('/api/users', userRoutes);
// Swagger
const swaggerOptions = {
definition: {
openapi: '3.0.0',
info: {
title: 'API Documentation',
version: '1.0.0',
},
},
apis: ['./src/routes/*.js', './src/swagger/*.js'],
};
const swaggerSpec = swaggerJsdoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.listen(3000, () => {
console.log('Server running on port 3000');
});Best Practices
- Always use schema files - Don't manually write CRUD code
- Validate schemas - Run
echo-crud-factory checkbefore generating - Use dry-run - Preview files with
--dry-runflag - Version control schemas - Keep schema files in git
- Review generated code - Always review before committing
- Run migrations - Don't forget to run database migrations
- Test endpoints - Use generated Swagger docs for testing
Troubleshooting
Node.js Version Error
✗ Node.js v22 or higher is requiredSolution: Upgrade Node.js to v22 or higher.
Schema Validation Failed
✗ Column name "firstName" must be in snake_case formatSolution: Use snake_case for all column names: first_name.
File Already Exists
✗ File already exists: src/controllers/user.controller.jsSolution: Use --force flag to overwrite or manually delete the file.
Missing Dependencies
✗ Required dependency not found: sequelizeSolution: Install required dependencies:
npm install sequelize mysql2Roadmap
- [ ] TypeORM model generator
- [ ] Prisma schema generator
- [ ] Service layer generator
- [ ] Repository layer generator
- [ ] Test file generator
- [ ] OpenAPI to Postman export
- [ ] Custom template support
- [ ] Plugin system
- [ ] GraphQL support
Contributing
Contributions are welcome! Please read our Contributing Guide for details.
License
MIT © Master Builder Team
Built with ❤️ for backend developers who value consistency and quality.
