Commands
Complete reference for all SargenJS commands and their options.
Initialization
sargen init <project-name>Create a new Express.js project with the specified name and structure.
Options:
--struct <type>Project structure type: layered or modular (default: layered)--testAdd test routing file to demonstrate project structure and API handling patterns--security [security...]Setup security middlewares: rateLimit-v, --verboseEnable verbose logging to see detailed background processesExamples:
1. Basic Project Creation:
sargen init my-app• Creates project with default layered structure
• Includes basic Express.js setup with security middlewares
2. Complete Workflow Example:
sargen init my-app --struct modular --testcd my-appnpm run dev• Creates modular structure project with test routing
• Navigate to project directory
• Start development server on http://localhost:8000
• Test endpoint available at: http://localhost:8000/api/v1/test/test-api
About Test Endpoint:
The --test flag creates a test routing file to demonstrate the project structure and API handling patterns. It's designed to help you understand how routes, controllers, and responses work in your chosen architecture (layered or modular).
Setup (within existing project)
sargen setupConfigure an existing Express.js project to use SargenJS commands.Validates that you're in a proper Express.js project directory.
Validation Checks:
- • Valid package.json with Express.js dependency
- • Standard Express.js project structure
- • Warns about missing recommended dependencies
Options:
-v, --verboseEnable verbose logging to see detailed background processesWhat it does:
- • Detects project structure (layered or modular)
- • Creates
.sargen.jsonconfiguration file - • Enables use of other sargen commands in the project
Important Note:
For best results, ensure your existing Node.js project has a structure similar to SargenJS (Express.js with organized folders like src/,routes/,controllers/, etc.). This ensures other SargenJS commands work accurately with your project structure.
Database Configuration
sargen gen:dbConfigure database ORM and adapter setup (Sequelize and MySQL by default).
Options:
--orm <name>Database ORM: sequelize (TypeORM support coming soon)--adapter <name>Database adapter: mysql or postgres--dockerSet up database with Docker Compose configuration (creates local database containers)-v, --verboseEnable verbose logging to see detailed background processesExamples:
1. Setup with MySQL (default):
sargen gen:db• Creates Sequelize configuration with MySQL adapter
• Generates database connection setup
2. Setup with PostgreSQL:
sargen gen:db --adapter postgres• Creates Sequelize configuration with PostgreSQL adapter
• Generates database connection setup
3. Setup with Docker (MySQL - Default):
sargen gen:db --docker• Creates MySQL 8.0 Docker container with optimized configuration
• Generates secure random passwords for database access
• Configures database credentials in Docker Compose
• Creates Docker Compose configuration in docker/ directory
// Generated files: docker/docker-compose.yml docker/data/mysql/ (data persistence) // Start database: docker-compose -f docker/docker-compose.yml up -d // Database credentials configured in docker-compose.yml DB_PASSWORD=<generated-secure-password> DB_PORT=3306 DB_HOST=localhost
4. Setup with Docker (PostgreSQL):
sargen gen:db --docker --adapter postgres• Creates PostgreSQL 17 Docker container with optimized configuration
• Generates secure random passwords for database access
• Configures database credentials in Docker Compose
• Creates Docker Compose configuration in docker/ directory
// Generated files: docker/docker-compose.yml docker/data/postgres/ (data persistence) // Start database: docker-compose -f docker/docker-compose.yml up -d // Database credentials configured in docker-compose.yml DB_PASSWORD=<generated-secure-password> DB_PORT=5432 DB_HOST=localhost
Docker Database Features:
🔒 Security:
- • Secure random password generation
- • Environment-specific credentials
- • Health checks for container monitoring
⚡ Performance:
- • Optimized database configurations
- • Data persistence with volumes
- • Network isolation with Docker networks
📋 Quick Start:
sargen gen:db --dockerdocker-compose -f docker/docker-compose.yml up -dnpx sequelize-cli db:migrateHow to Use in Your Project:
1. Create a model:
npx sequelize-cli model:generate --name User --attributes name:string,email:string2. Run migrations:
npx sequelize-cli db:migrate3. Use in your controller:
const db= require('../models');
const usersModel = db.users;
// Get all users
const users = await usersModel.findAll();
// Create new user
const newUser = await usersModel.create({
name: 'John Doe',
email: 'john@example.com'
});The setup creates src/config/config.jsonand organizes models/,migrations/,seeders/ directories.
Module Generation
sargen gen:module <module-name>Generate a new module/feature with all necessary files (controller, route, service, model). Three progressive use cases available:
Note: For consistency, keep module names in plural form or close to table names (e.g., users, orders, products, payments).
1. Basic Module Setup
sargen gen:module usersCreates blank controller, routes, service, and model files for customization
2. Module with CRUD Methods
sargen gen:module users --crudCreates module files with blank CRUD methods. Manual migration/model updates required.
3. Complete CRUD with Database Integration
sargen gen:module users --crud --model-attributes name:string,age:numberFully functional CRUD with dynamic queries and automatic pagination. Just run migrations and it's ready!
Options:
--crudGenerate Create, Read, Update, Delete APIs with the module--model-attributes <attributes>Define model attributes (format: name:string,email:string,phone:number)--no-modelSkip model generation (only create controller, route, service)-v, --verboseEnable verbose logging to see detailed background processesCRUD Endpoints (with --crud flag):
POST /api/v1/<module>GET /api/v1/<module>PUT /api/v1/<module>/:idDELETE /api/v1/<module>/:idExamples:
1. Basic Module Setup:
sargen gen:module users• Creates blank controller, route, service, model files
• User can customize files as per their requirements
2. Module with CRUD Methods:
sargen gen:module users --crud• Creates module files with blank CRUD methods
• Generates RESTful endpoints: POST, GET, PUT, DELETE
• Manual migration and model updates required
// Generated controller automatically calls service methods:
const getUsers = async (req, res) => {
try {
const result = await usersService.getUsers(req.query);
res.status(200).json(result);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
const createUser = async (req, res) => {
try {
const result = await usersService.createUser(req.body);
res.status(200).json(result);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Add your validations & business logic in service methods3. Complete CRUD with Database Integration:
sargen gen:module users --crud --model-attributes name:string,phone:number,dob:datesargen gen:module orders --crud --model-attributes "product_id:ref(products),status:enum(pending|completed|cancelled),quantity:integer"• Creates fully functional CRUD with dynamic queries
• Populates migration file with defined attributes
• Next step: Run npx sequelize-cli db:migrate and CRUD is ready to use
// Model with custom attributes (name, phone, dob):
const User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false
},
phone: {
type: DataTypes.BIGINT,
allowNull: true
},
dob: {
type: DataTypes.DATE,
allowNull: true
}
});
// Service methods with parameters:
const createUser = async (data) => {
try {
// TODO: Add your validations & business logic here
return {
success: true,
message: "Created successfully",
data: data
}
} catch (error) {
return { success: false, message: error.message }
}
};📋 Supported Data Types
Basic Types: string, number, integer, boolean, float, date
Foreign Keys: ref(modelName) - requires quoting for shell compatibility
Enums: enum(value1|value2|...) - up to 10 values, requires quoting
Example with foreign key and enum:
sargen gen:module orders --crud --model-attributes "product_id:ref(products),status:enum(pending|completed|cancelled)"Note: Always use quotes around attributes containing ref() or enum() to avoid shell syntax errors.
📄 Pagination Service
When using --crud and --model-attributes, SargenJS automatically creates a pagination service for GET operations.
Usage: GET /api/v1/users?page=1&limit=10
Response: Includes totalCounts, totalPages, currentPage, pageLimit, and items array
Middleware Setup
sargen gen:middleware <name>Setup predefined middleware code files into your project.
Options:
-v, --verboseEnable verbose logging to see detailed background processesAvailable Middlewares:
validator - Centralized validation service with auto-discoveryauth - JWT-based authentication systemacl - Role-based access control systemmonitor - Prometheus, Grafana, and Loki monitoring with Docker ComposeFile Locations:
src/middlewares/src/common/middlewares/Examples:
1. Validation Middleware:
sargen gen:middleware validator• Creates validationService.js and example.dto.js
• Auto-discovers DTO files from src/dto Or src/common/dto directory
• Uses `fastest-validator` (NPM package) for high-performance validation
// Create DTO file: src/dto/user.dto.js
module.exports = {
user_create_schema: {
name: { type: "string", min: 2, max: 50 },
email: { type: "email" },
age: { type: "number", positive: true, optional: true }
}
};
// Use in routes
const validationService = require('../middlewares/validationService');
router.post('/', validationService.validate('user_create_schema'), controller.create);2. JWT Authentication Middleware:
sargen gen:middleware auth• Creates authMiddleware.js and jwtService.js
• Installs jsonwebtoken and bcrypt dependencies
• Requires JWT_PASSPHRASE and JWT_EXPIRATION in .env
// .env file
JWT_PASSPHRASE=your_secret_passphrase
JWT_EXPIRATION=24h
// Sign in API (create token)
const jwtService = require('../middlewares/jwtService');
router.post('/signin', async (req, res) => {
const { email, password } = req.body;
// Validate user credentials...
const user = { id: 1, email: 'user@example.com' };
const token = jwtService.signToken(user);
res.json({ success: true, token });
});
// Protected route (verify token)
const authMiddleware = require('../middlewares/authMiddleware');
router.get('/profile', authMiddleware.authenticate, (req, res) => {
res.json({ user: req.user });
});
router.get('/admin-profile', authMiddleware.authenticateRole(['admin']), (req, res) => {
// this route is protected and only accessible to admin role
res.json({ user: req.user });
});3. Role-Based Access Control (ACL):
sargen gen:middleware acl• Creates aclMiddleware.js and acl.json
• Advanced layer over Auth: Provides granular file-based permission control
• Action-specific permissions: Control what authenticated users can do
• Role hierarchy: Define complex permission structures
🔐 Why ACL over Auth?
• Auth: "Is this user logged in?" (Authentication)
• ACL: "Can this authenticated user perform this specific action?" (Authorization)
• Example: Both admin and user are authenticated, but only admin can delete users
// src/config/acl.json - Advanced role-based permissions
{
"roles": {
"admin": {
"resources": {
"users": ["create", "read", "update", "delete"],
"files": ["create", "read", "update", "delete"]
}
},
"editor": {
"resources": {
"users": ["read"],
"files": ["create", "read", "update"]
}
},
"viewer": {
"resources": {
"users": ["read"],
"files": ["read"]
}
}
}
}
// Use in routes - Resource-based permission control
const aclMiddleware = require('../middlewares/aclMiddleware');
// Admin can delete users, editor can only read
router.delete('/users/:id', aclMiddleware('users', 'delete'), (req, res) => {
res.json({ message: 'User deleted by admin' });
});
// Editor can update files, viewer can only read
router.put('/files/:id', aclMiddleware('files', 'update'), (req, res) => {
res.json({ message: 'File updated by editor' });
});
// Multiple resource permissions
router.get('/dashboard', aclMiddleware(['users', 'files'], 'read'), (req, res) => {
res.json({ message: 'Dashboard data' });
});🚀 Real-World Use Cases:
• E-commerce: Customer (read products), Seller (manage products), Admin (full access)
• CMS: Viewer (read content), Editor (create/update content), Admin (manage users)
• Enterprise: Employee (view data), Manager (approve requests), Admin (system access)
• File Management: Viewer (read files), Editor (upload/update files), Admin (delete files)
4. Monitoring Stack:
sargen gen:middleware monitor• Creates complete monitoring setup with Prometheus, Grafana, Loki
• Includes docker-compose.yml for easy deployment
• Creates monitorMiddleware.js for metrics collection
// Start monitoring stack (centralized Docker)
docker-compose -f docker/docker-compose.yml up -d
// Setup in your app.js
const { attachMonitoring, logger } = require('./middlewares/monitorMiddleware');
// Attach monitoring to your Express app
attachMonitoring(app); // API Request & Error logging
// Use custom 'logger' in your routes (Winston logger)
router.get('/api/users', (req, res) => {
logger.info('Fetching users');
res.json({ users: [] });
});
// Access dashboards
Prometheus: http://localhost:9090
Grafana: http://localhost:3000
Loki: http://localhost:8080
Metrics: http://localhost:8000/metricsMonitor Middleware Features:
docker/ directory with Docker Composehttp://localhost:3000docker-compose -f docker/docker-compose.yml up -dUtility Services
sargen gen:util <util-name>Generate utility services for your project.
Available Utilities:
smtp - SMTP email service with Nodemailernotification - Push notification service with Firebase Admin SDKredis - Redis connection and service utilitiesfileupload - File upload service with Multer (local, AWS S3, or Google Cloud Storage)Options:
--dockerGenerate utility with Docker Compose file--cloud <provider>Cloud provider for fileupload (aws or gcp). If not provided, uses local storage.-v, --verboseEnable verbose logging to see detailed background processesFile Locations:
src/utils/src/common/utils/Examples:
1. SMTP Email Service:
sargen gen:util smtp• Creates emailService.js with Nodemailer
• Installs nodemailer dependency
• Configurable for Gmail, SendGrid, and other SMTP providers
// .env configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password
SMTP_SECURE=false
SMTP_FROM_NAME=Your App Name
// Use in your routes
const emailService = require('../utils/emailService');
// Send welcome email
await emailService.sendWelcomeEmail('user@example.com', 'John Doe');
// Send custom email
await emailService.sendEmail({
to: 'user@example.com',
subject: 'Hello World',
text: 'This is a test email'
});2. Push Notification Service:
sargen gen:util notification• Creates notificationService.js with Firebase Admin SDK
• Installs firebase-admin dependency
• Supports FCM for Android, iOS, and web push notifications
// .env configuration
FIREBASE_SERVICE_ACCOUNT_PATH=./path/to/your-service-account.json
FIREBASE_DATABASE_URL=https://your-project.firebaseio.com
// Download service account file from:
// Firebase Console > Project Settings > Service Accounts > Generate New Private Key
// Use in your routes
const notificationService = require('../utils/notificationService');
// Send to single device
await notificationService.sendToDevice(
'device-token-here',
{ title: 'Hello!', body: 'This is a test notification' }
);
// Send to multiple devices
await notificationService.sendToMultipleDevices(
['token1', 'token2'],
{ title: 'Broadcast', body: 'Message to all users' }
);
// Send to topic
await notificationService.sendToTopic(
'news',
{ title: 'Breaking News', body: 'Important update' }
);3. Redis Utility Service:
sargen gen:util redis• Creates redisService.js with connection utilities
• Installs ioredis dependency
• Ready-to-use Redis connection and service methods
• Supports rate limiting middleware with Redis store
// Basic Redis operations
const redisService = require('../utils/redisService');
// Set data
await redisService.set('key', 'value', 3600);
// Get data
const data = await redisService.get('key');
// Delete data
await redisService.del('key');
// Redis Rate Limiting Middleware
const { createRateLimitService } = require('../utils/redisService');
const rateLimitService = createRateLimitService();
// Apply rate limiting (100 requests per 15 minutes)
app.use('/api/', rateLimitService.rateLimitMiddleware(100, 900));
// Cache Middleware
const { createCacheMiddleware } = require('../utils/redisService');
app.use('/api/', createCacheMiddleware());4. Redis with Docker Setup:
sargen gen:util redis --docker• Creates Redis service + centralized Docker Compose configuration
• Includes docker-compose.yml in docker/ directory
• Usage: docker-compose -f docker/docker-compose.yml up -d
docker-compose -f docker/docker-compose.yml up -d
const redisService = require('../utils/redisService');
await redisService.set('key', 'value');Docker Features:
docker/ directory with Docker Composelocalhost:6379docker-compose -f docker/docker-compose.yml up -d5. File Upload Service (Local Storage):
sargen gen:util fileupload• Creates file upload service with Multer
• Installs multer dependency
• Supports images, videos, and documents
• Files stored in ./uploads directory
const FileUploadService = require('../utils/fileupload/fileUploadService');
const uploadService = new FileUploadService({
storage: 'local',
maxFileSize: '10MB'
});
router.post('/upload', uploadService.middleware('file'), async (req, res) => {
res.json({ success: true, file: req.file });
});6. File Upload Service (AWS S3):
sargen gen:util fileupload --cloud aws• Creates file upload service with AWS S3 integration
• Installs multer, @aws-sdk/client-s3, @aws-sdk/s3-request-presigner
• Files uploaded directly to S3 bucket
// .env: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, AWS_S3_BUCKET
const uploadService = new FileUploadService({
storage: 's3',
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION,
bucket: process.env.AWS_S3_BUCKET
});
router.post('/upload', uploadService.middleware('file'), async (req, res) => {
const result = await uploadService.upload(req.file);
const url = await uploadService.getFileSignedUrl(result.filename, 3600);
res.json({ success: true, url });
});7. File Upload Service (Google Cloud Storage):
sargen gen:util fileupload --cloud gcp• Creates file upload service with Google Cloud Storage integration
• Installs multer, @google-cloud/storage
• Files uploaded directly to GCS bucket
// .env: GCP_BUCKET, GCP_PROJECT_ID, GCP_KEY_FILENAME
const uploadService = new FileUploadService({
storage: 'gcp',
bucket: process.env.GCP_BUCKET,
projectId: process.env.GCP_PROJECT_ID,
keyFilename: process.env.GCP_KEY_FILENAME // Service account JSON file Path
});
router.post('/upload', uploadService.middleware('file'), async (req, res) => {
const result = await uploadService.upload(req.file);
const url = await uploadService.getFileSignedUrl(result.filename, 3600);
res.json({ success: true, url });
});Git Setup
sargen gen:gitInitialize git repository and setup remote with automatic GitHub repository creation.
Options:
--remote <url>Remote repository URL (GitHub/GitLab/Bitbucket)--branch <name>Initial branch name (default: main)--message <msg>Custom initial commit message--publicCreate public repository (default: private)--description <desc>Repository description--no-pushInitialize git but don't push to remote-v, --verboseEnable verbose logging to see detailed background processesFeatures:
- • Auto-creates GitHub repository if no remote provided (requires GitHub CLI)
- • Automatically detects git installation and configuration
- • Fault-tolerant setup with graceful error handling
- • Supports all major git hosting services
- • Preserves existing project files and structure
- • Creates initial commit with all project files
Examples:
1. Basic Git Setup:
sargen gen:git• Initializes git repository with initial commit
• Creates private GitHub repository automatically (if GitHub CLI is available)
• Pushes code to main branch
// If GitHub CLI is installed: git init git add . git commit -m "Initial commit: Project Setup" git branch -M main gh repo create project-name --private git remote add origin https://github.com/username/project-name.git git push -u origin main // If GitHub CLI is NOT installed: git init git add . git commit -m "Initial commit: Project Setup" git branch -M main // Repository created locally, ready to push to remote
2. Git Setup with Existing Repository:
sargen gen:git --remote https://github.com/username/repo.git• Uses existing remote repository URL
• Initializes git and pushes to specified remote
• Perfect for connecting to existing GitHub/GitLab repositories
// Connects to existing repository: git init git add . git commit -m "Initial commit: Project Setup" git remote add origin https://github.com/username/repo.git git push -u origin main
3. Custom Branch and Message:
sargen gen:git --branch develop --message "My First Push"• Creates new develop branch
• Uses custom commit message
• Pushes to new branch without affecting main branch
// Creates new branch with custom message: git init git add . git commit -m "My First Push" git checkout -b develop git push -u origin develop
Docker Integration
SargenJS provides seamless Docker integration for development services with a centralized approach.
Centralized Docker Structure:
Available Docker Services:
Database
sargen gen:db --dockerMySQL 8.0 or PostgreSQL 17
Monitoring
sargen gen:middleware monitorPrometheus, Grafana, Loki
Redis
sargen gen:util redis --dockerRedis 7 with persistence
Quick Start:
sargen gen:db --dockersargen gen:middleware monitorsargen gen:util redis --dockerdocker-compose -f docker/docker-compose.yml up -d🚀 All services start with a single command! Access your services:
• Database: localhost:3306 (MySQL) / localhost:5432 (PostgreSQL)
• Redis: localhost:6379
• Grafana: http://localhost:3000
• Prometheus: http://localhost:9090
Typical Workflow
sargen init my-appsargen gen:db --adapter postgressargen gen:module users --crudsargen gen:git