flenco-node-backend-cli
v0.1.12
Published
CLI tool to generate complete backend projects with Express, TypeScript, and Prisma
Maintainers
Readme
Flenco Node Backend CLI
A powerful CLI tool to generate production-ready Node.js backends with Express, TypeScript, and Prisma. It automatically creates CRUD operations with validation, authentication, and file upload capabilities based on your existing database schema.
🚀 Features
- 🔥 Fast project setup with step-by-step guidance
- 📝 TypeScript support with strict mode enabled
- 🔐 JWT Authentication with login/logout API generation
- 📊 Prisma ORM integration with automatic client generation
- ✨ Automatic CRUD generation for any database table
- 📝 Request validation with Zod schemas
- 🔄 Built-in pagination and sorting for all list endpoints
- 🛠️ File upload support with configurable options
- 📧 Email service integration ready to use
- 🔍 Smart search functionality across all table fields
- 🎯 Clean architecture with separation of concerns
- 📚 API metadata endpoint for automatic documentation
- 📦 Automatic Postman collection generation
- ⚙️ User configuration system for customized experience
- 🎨 Progress indicators and enhanced UX
📋 Prerequisites
- Node.js >= 14 (Latest LTS recommended)
- npm >= 6 or yarn >= 1.22
- PostgreSQL or MySQL database
- Basic knowledge of TypeScript and REST APIs
📦 Installation
# Install globally
npm install -g flenco-node-backend-cli
# Or using yarn
yarn global add flenco-node-backend-cli🏃♂️ Quick Start
1. Initialize a New Project
# Create a new directory for your project
mkdir my-awesome-backend
cd my-awesome-backend
# Initialize the project (interactive setup)
flenco-initThe initialization process will:
- ✅ Check your environment (Node.js version, directory status)
- 📝 Prompt for project configuration (database, credentials)
- 🏗️ Create project structure
- 📦 Install dependencies automatically
- 🔧 Generate configuration files
- 🎯 Find available ports automatically
- 📄 Create Postman collection for testing
2. Generate APIs for Your Tables
# Generate CRUD APIs for database tables
flenco-generateThis command will:
- 🔍 Introspect your database schema
- 📋 Show available tables to choose from
- ⚙️ Ask for authentication and file upload preferences
- 🏭 Generate complete CRUD operations
- 🔍 Add automatic search functionality across all fields
- 📱 Update Postman collection with new endpoints
3. Generate Authentication APIs (Optional)
During the flenco-generate process, you'll be asked:
🔐 Do you want to generate login/logout APIs? (y/N)If you choose Yes:
- 📋 Select the user table (users, accounts, etc.)
- 🔑 Choose login field (email, username, mobile)
- 🛡️ Automatic JWT token generation
- 🚪 Login and logout endpoints created
- 🔒 Password hashing with bcrypt
4. Refresh APIs When Schema Changes
# Update existing APIs when database schema changes
flenco-refreshThis preserves your customizations while updating:
- 🔄 Field definitions
- 🔍 Search capabilities
- 📊 Validation schemas
- 🛡️ Authentication settings
🛠️ Available Commands
| Command | Description | Usage |
|---------|-------------|-------|
| flenco-init | Initialize a new backend project | flenco-init |
| flenco-generate | Generate APIs for database tables | flenco-generate |
| flenco-refresh | Refresh APIs after schema changes | flenco-refresh |
| flenco-help | Show detailed help and usage info | flenco-help |
| flenco-config | Manage CLI configuration | flenco-config show |
| flenco | Main command (shows options) | flenco |
⚙️ Configuration System
Customize your experience with the configuration system:
# Show current configuration
flenco-config show
# Set default database type
flenco-config set defaultDatabase postgresql
# Set default host
flenco-config set defaultHost localhost
# Skip Node.js version checks
flenco-config set skipNodeVersionCheck true
# Disable automatic dependency installation
flenco-config set autoInstallDependencies false
# Reset to defaults
flenco-config resetAvailable Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| defaultDatabase | postgresql\|mysql | postgresql | Default database type |
| defaultHost | string | localhost | Default database host |
| defaultPort | number | 5432\|3306 | Default database port |
| skipNodeVersionCheck | boolean | false | Skip Node.js version validation |
| autoInstallDependencies | boolean | true | Auto-install npm packages |
| generateTests | boolean | false | Generate test files (future) |
| preferredCodeStyle | string | standard | Code formatting preference |
🏗️ Generated Project Structure
my-backend/
├── src/
│ ├── routes/ # API route definitions
│ │ ├── index.ts # Main router
│ │ ├── metadata.route.ts # API documentation endpoint
│ │ ├── auth.route.ts # Authentication routes (if generated)
│ │ └── users.route.ts # Generated table routes
│ ├── controllers/ # Request handlers
│ │ ├── base.controller.ts
│ │ ├── auth.controller.ts
│ │ └── users.controller.ts
│ ├── services/ # Business logic layer
│ │ ├── base.service.ts
│ │ ├── auth.service.ts
│ │ └── users.service.ts
│ ├── middleware/ # Custom middleware
│ │ ├── auth.middleware.ts
│ │ ├── error.middleware.ts
│ │ ├── upload.middleware.ts
│ │ └── validate.middleware.ts
│ ├── validation/ # Zod schemas
│ │ ├── base.validation.ts
│ │ ├── common.validation.ts
│ │ ├── auth.validation.ts
│ │ └── users.validation.ts
│ ├── utils/ # Utility functions
│ │ ├── response.util.ts
│ │ ├── jwt.util.ts
│ │ ├── email.utils.ts
│ │ └── upload.util.ts
│ ├── types/ # TypeScript definitions
│ │ └── global.d.ts
│ ├── app.ts # Express app configuration
│ └── server.ts # Server entry point
├── prisma/ # Database schema and migrations
│ └── schema.prisma # Prisma schema file
├── uploads/ # File upload directory
├── api-collection.json # Postman collection
├── .env # Environment variables
├── package.json # Dependencies and scripts
└── tsconfig.json # TypeScript configuration🌐 Generated API Endpoints
Standard CRUD Operations
For each table (e.g., users):
| Method | Endpoint | Description | Features |
|--------|----------|-------------|----------|
| GET | /api/users | List all records | 📄 Pagination, 🔍 Search, 📊 Sorting |
| GET | /api/users/:id | Get single record | 🎯 By ID |
| POST | /api/users | Create new record | ✅ Validation, 📁 File upload |
| PATCH | /api/users/:id | Update record | ✅ Partial updates |
| DELETE | /api/users/:id | Delete record | 🗑️ Soft/hard delete |
Authentication Endpoints (if generated)
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | /api/auth/login | User login |
| POST | /api/auth/logout | User logout |
| POST | /api/auth/refresh | Refresh JWT token |
| GET | /api/auth/profile | Get user profile |
System Endpoints
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /api/metadata | API documentation |
| GET | /health | Health check |
🔍 Smart Search Functionality
All list endpoints automatically support searching across all text fields in your table:
# Search across all searchable fields
GET /api/users?search=john
# Search with pagination
GET /api/users?search=admin&page=1&limit=10
# Search with sorting
GET /api/users?search=active&sortBy=createdAt&sortOrder=descAutomatically searchable field types:
Stringfields (name, email, description, etc.)TextfieldsVarcharfields
📊 Query Parameters
All list endpoints support these query parameters:
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| page | number | 1 | Page number for pagination |
| limit | number | 10 | Items per page (max 100) |
| search | string | - | Search across all text fields |
| sortBy | string | createdAt | Field to sort by |
| sortOrder | asc\|desc | desc | Sort direction |
| status | string | - | Filter by status (if field exists) |
Example Requests
# Get users with pagination
GET /api/users?page=2&limit=20
# Search for users
GET /api/users?search=john&limit=5
# Sort users by email
GET /api/users?sortBy=email&sortOrder=asc
# Complex query
GET /api/users?search=active&page=1&limit=10&sortBy=createdAt&sortOrder=desc🔐 Authentication
JWT Token Usage
// Include in headers for protected routes
{
"Authorization": "Bearer your-jwt-token-here"
}Login Request Example
# Login with email
POST /api/auth/login
{
"email": "[email protected]",
"password": "yourpassword"
}
# Login with username
POST /api/auth/login
{
"username": "johndoe",
"password": "yourpassword"
}
# Login with mobile
POST /api/auth/login
{
"mobile": "+1234567890",
"password": "yourpassword"
}Response Format
{
"status": "success",
"message": "Login successful",
"data": {
"user": {
"id": 1,
"email": "[email protected]",
"name": "John Doe"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expiresIn": "1d"
}
}📁 File Upload
Configure file uploads in your .env:
# File Upload Configuration
MAX_FILE_SIZE=5242880 # 5MB in bytes
ALLOWED_FILE_TYPES=image/jpeg,image/png,image/gif,application/pdf
UPLOAD_PATH=uploadsUpload Example
POST /api/users
Content-Type: multipart/form-data
{
"name": "John Doe",
"email": "[email protected]",
"avatar": [file] # File upload field
}🛠️ Development Workflow
Starting Development
# Start development server with hot reload
npm run dev
# Build for production
npm run build
# Start production server
npm startEnvironment Variables
Essential environment variables in .env:
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
PORT=3000
# JWT Configuration
JWT_SECRET=your-super-secret-key-change-this
JWT_EXPIRES_IN=1d
# Email Configuration (optional)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
[email protected]
SMTP_PASS=your-app-password
[email protected]
# File Upload
MAX_FILE_SIZE=5242880
ALLOWED_FILE_TYPES=image/jpeg,image/png,image/gif
UPLOAD_PATH=uploads
# Frontend URL (for CORS and email links)
FRONTEND_URL=http://localhost:3000📚 API Documentation
Auto-generated Documentation
Visit /api/metadata to get comprehensive API documentation including:
- 📋 All available endpoints
- 📝 Request/response schemas
- 🔍 Parameter descriptions
- 📊 Example requests
Postman Collection
Import the auto-generated api-collection.json file into Postman for:
- 🚀 Ready-to-use requests
- 🔧 Pre-configured environment variables
- 📝 Request examples
- 🧪 Testing workflows
🔧 Customization
Adding Custom Logic
// src/services/users.service.ts
export class UsersService extends BaseService {
// Add custom methods
async findByEmail(email: string) {
return this.findFirst({ email });
}
// Override default behavior
async create(data: any) {
// Custom validation or processing
const processedData = this.processUserData(data);
return super.create(processedData);
}
}Custom Validation
// src/validation/users.validation.ts
export const createUserSchema = z.object({
name: z.string().min(2).max(50),
email: z.string().email(),
age: z.number().min(18).max(120).optional(),
// Add custom validation rules
});Custom Middleware
// src/middleware/custom.middleware.ts
export const customAuthMiddleware = (req: Request, res: Response, next: NextFunction) => {
// Custom authentication logic
next();
};🧪 Testing
API Testing with Postman
- Import
api-collection.jsoninto Postman - Set environment variables:
baseUrl:http://localhost:3000token: Your JWT token after login
- Test all endpoints with pre-configured requests
Manual Testing Examples
# Test user creation
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"[email protected]"}'
# Test authentication
curl -X POST http://localhost:3000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"password123"}'
# Test protected endpoint
curl -X GET http://localhost:3000/api/users \
-H "Authorization: Bearer your-jwt-token"🚀 Deployment
Environment Setup
Production Environment Variables
NODE_ENV=production DATABASE_URL=your-production-db-url JWT_SECRET=your-production-secret PORT=3000Build and Start
npm run build npm start
Docker Deployment (Optional)
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
EXPOSE 3000
CMD ["node", "dist/server.js"]🤝 Contributing
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
Development Setup
# Clone the repository
git clone https://github.com/flenco-in/flenco-node-backend-cli.git
cd flenco-node-backend-cli
# Install dependencies
npm install
# Build the project
npm run build
# Link for local testing
npm link📋 Changelog
v0.1.11 (Latest)
- ✅ Enhanced user experience with progress indicators
- ✅ Added configuration system for user preferences
- ✅ Automatic search field generation from table schema
- ✅ Optional login/logout API generation
- ✅ Improved error handling and validation
- ✅ Smart port detection and project name suggestion
- ✅ Comprehensive help system
- ✅ Updated dependencies to latest versions
Previous Versions
- See CHANGELOG.md for detailed version history
❓ FAQ
Q: Can I use this with an existing database? A: Yes! The CLI works perfectly with existing databases. It will introspect your schema and generate APIs accordingly.
Q: How do I add custom validation rules?
A: Edit the generated validation files in src/validation/ to add custom Zod schemas.
Q: Can I modify the generated code?
A: Absolutely! The generated code is meant to be customized. Use flenco-refresh to update APIs while preserving your changes.
Q: Which databases are supported? A: Currently PostgreSQL and MySQL. Support for more databases is planned.
Q: How do I handle database migrations?
A: Use Prisma migrations: npx prisma migrate dev for development and npx prisma migrate deploy for production.
🐛 Troubleshooting
Common Issues
Issue: "Command not found: flenco-init"
# Solution: Install globally or check PATH
npm install -g flenco-node-backend-cli
# or
npx flenco-node-backend-cli initIssue: Database connection errors
# Solution: Check your DATABASE_URL in .env
# Ensure database server is running
# Verify credentials and permissionsIssue: Port already in use
# Solution: The CLI automatically finds available ports
# Or manually set PORT in .env fileIssue: TypeScript compilation errors
# Solution: Ensure dependencies are installed
npm install
npm run buildFor more issues, visit our GitHub Issues page.
📞 Support
- 📖 Documentation: GitHub Repository
- 🐛 Bug Reports: GitHub Issues
- 💬 Discussions: GitHub Discussions
- 📧 Email: [email protected]
- ☕ Support the Project: Buy Me A Coffee
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Prisma for the amazing ORM
- Express for the web framework
- Zod for schema validation
- Commander.js for CLI functionality
- Inquirer.js for interactive prompts
Made with ❤️ by Atish Paul
Star ⭐ this repository if it helped you build amazing backends faster!
