cube-ms
Version:
Production-ready microservice framework with health monitoring, validation, error handling, and Docker Swarm support
540 lines (381 loc) ⢠10.2 kB
Markdown
# Cube-MS CLI Documentation
The Cube-MS CLI provides a complete development experience, with interactive project scaffolding, multi-database configuration, TypeScript support, and comprehensive code generation tools.
## Installation
```bash
# Install globally
npm install -g cube-ms
# Or use with npx
npx cube-ms <command>
```
## Quick Start
### Interactive Project Creation
```bash
# Interactive setup with step-by-step configuration
cube-ms create my-app
# Non-interactive with defaults
cube-ms create my-app --no-interactive
# Specify language upfront
cube-ms create my-app --language typescript --port 8080
# Skip dependency installation
cube-ms create my-app --skip-install
```
The interactive mode guides you through:
1. **Language Selection**: Choose JavaScript or TypeScript
2. **Port Configuration**: Set your server port
3. **Database Setup**: Single or multi-database configuration
4. **Template Selection**: Choose your project template
**Interactive Experience:**
```
šÆ Setting up your cube-ms project: my-app
Use arrow keys to navigate, Enter to select
1/5 Choose your programming language:
⯠š” JavaScript
šµ TypeScript
2/5 Configure server port:
? Enter port number: (3000)
3/5 Configure database connection:
⯠š¦ Single Database - Standard MongoDB connection
šļø Multiple Databases - Connect to multiple MongoDB instances
4/5 Choose project template:
⯠š§ Basic - Simple REST API with health checks
š API - Full-featured API with authentication
```
### Available Templates
- **basic** - Simple microservice with health checks and basic routing
- **api** - RESTful API with user management, authentication, and CRUD operations
- **fullstack** - Full-stack application with frontend integration (coming soon)
## Project Structure
When you create a new project, you get a consistent folder structure:
```
my-app/
āāā src/
ā āāā config/ # Configuration files
ā ā āāā app.config.js # Main app configuration
ā āāā controllers/ # Request controllers
ā āāā services/ # Business logic services
ā āāā models/ # Data models and schemas
ā āāā routes/ # Route definitions
ā ā āāā index.js # Route setup
ā ā āāā api.routes.js # API routes
ā ā āāā health.routes.js # Health routes
ā āāā middleware/ # Custom middleware
ā āāā utils/ # Utility functions
ā āāā index.js # Application entry point
āāā test/ # Test files
āāā scripts/ # Utility scripts
āāā .env.example # Environment template
āāā cube-ms.config.js # Framework configuration
āāā package.json
āāā Dockerfile
āāā docker-compose.yml
āāā README.md
```
## CLI Commands
### Project Management
#### `cube-ms create <name> [options]`
Create a new Cube-MS project.
**Options:**
- `-t, --template <template>` - Project template (basic, api, fullstack)
- `--skip-install` - Skip npm install
**Examples:**
```bash
cube-ms create my-service
cube-ms create my-api --template api
cube-ms create my-project --skip-install
```
#### `cube-ms init [options]`
Initialize Cube-MS in an existing project.
**Options:**
- `-f, --force` - Overwrite existing files
**Examples:**
```bash
cube-ms init
cube-ms init --force
```
### Development Commands
#### `cube-ms dev [options]`
Start development server with hot reload.
**Options:**
- `-p, --port <port>` - Port number (default: 3000)
- `-w, --watch` - Enable file watching (default: true)
**Examples:**
```bash
cube-ms dev
cube-ms dev --port 8080
cube-ms dev --no-watch
```
#### `cube-ms build [options]`
Build project for production.
**Options:**
- `-o, --output <dir>` - Output directory (default: dist)
**Examples:**
```bash
cube-ms build
cube-ms build --output build
```
#### `cube-ms start [options]`
Start production server.
**Options:**
- `-p, --port <port>` - Port number (default: 3000)
- `-c, --cluster` - Enable cluster mode
**Examples:**
```bash
cube-ms start
cube-ms start --port 8080 --cluster
```
### Code Generation
#### `cube-ms generate <type> <name> [options]`
Generate components, services, models, routes, and more.
**Alias:** `cube-ms g`
**Options:**
- `-p, --path <path>` - Target directory (default: current)
**Available Types:**
##### Service Generation
```bash
cube-ms generate service user
cube-ms g service payment
```
Generates a service class with CRUD operations, logging, and error handling.
##### Controller Generation
```bash
cube-ms generate controller user
cube-ms g controller product
```
Generates a REST controller with standard CRUD endpoints.
##### Model Generation
```bash
cube-ms generate model user
cube-ms g model product
```
Generates a data model with validation schema and helper methods.
##### Route Generation
```bash
cube-ms generate route user
cube-ms g route auth
```
Generates route handlers with validation and error handling.
##### Middleware Generation
```bash
cube-ms generate middleware auth
cube-ms g middleware cors
```
Generates custom middleware with proper error handling.
## Configuration
### cube-ms.config.js
The main configuration file for your project:
```javascript
export default {
name: "my-app",
version: "1.0.0",
dev: {
port: 3000,
watch: ["src/**/*.js"],
env: {
NODE_ENV: "development",
},
},
service: {
features: {
security: { enabled: true, level: "standard" },
rateLimit: { enabled: true, preset: "moderate" },
monitoring: { enabled: true },
},
},
generators: {
service: { path: "src/services" },
controller: { path: "src/controllers" },
},
};
```
### Environment Variables
Create a `.env` file for environment-specific configuration:
```bash
# Application
APP_NAME=MyApp
SERVICE_NAME=my-service
NODE_ENV=development
PORT=3000
# Database
MONGODB_URL=mongodb://localhost:27017/myapp
# Security
SECURITY_LEVEL=standard
RATE_LIMIT_PRESET=moderate
# Monitoring
MONITORING_ENABLED=true
```
## Development Workflow
### 1. Create Project
```bash
cube-ms create my-api --template api
cd my-api
```
### 2. Start Development
```bash
npm run dev
# or
cube-ms dev
```
### 3. Generate Components
```bash
# Generate a new feature
cube-ms generate service product
cube-ms generate controller product
cube-ms generate route product
cube-ms generate model product
```
### 4. Test Your API
```bash
npm test
```
### 5. Build for Production
```bash
cube-ms build
cube-ms start
```
## Generated Code Examples
### Service Example
```javascript
export class ProductService {
constructor() {
this.logger = CreateLogger("ProductService", "service", "container");
}
async create(data) {
try {
this.logger.info("Creating product", { data });
// Implementation here
return { success: true, data };
} catch (error) {
this.logger.error("Error creating product", { error: error.message });
throw error;
}
}
}
```
### Controller Example
```javascript
export class ProductController {
static create = asyncHandler(async (req, res, logger) => {
const result = await ProductService.create(req.body);
logger.info("Product created", { id: result.id });
res.status(201).json({ success: true, data: result });
});
}
```
### Route Example
```javascript
export const setupProductRoutes = (service) => {
service.addRoute(
"post",
"/products",
[validate({ body: ProductSchema })],
ProductController.create
);
};
```
## Docker Integration
Generated projects include Docker configuration:
### Development
```bash
docker-compose up -d
```
### Production
```bash
docker build -t my-app .
docker run -p 3000:3000 my-app
```
## Testing
Run tests with:
```bash
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # With coverage
```
## Best Practices
### 1. Project Organization
- Keep business logic in services
- Use controllers for HTTP handling
- Define clear data models
- Organize routes logically
### 2. Code Generation
- Generate related components together
- Follow naming conventions
- Customize generated code as needed
### 3. Configuration
- Use environment variables for configuration
- Keep sensitive data in `.env`
- Use different configs for different environments
### 4. Development
- Use `cube-ms dev` for development
- Generate components instead of writing from scratch
- Test regularly during development
## Advanced Usage
### Custom Templates
You can create custom templates in the `templates/` directory:
```
templates/
āāā my-template/
ā āāā package.json
ā āāā src/
ā āāā ...
```
Then use:
```bash
cube-ms create my-project --template my-template
```
### Custom Commands
Add custom commands to your `cube-ms.config.js`:
```javascript
export default {
commands: {
seed: "node scripts/seed.js",
migrate: "node scripts/migrate.js",
"custom-task": "node scripts/my-task.js",
},
};
```
### Integration with CI/CD
```yaml
# GitHub Actions example
- name: Install cube-ms
run: npm install -g cube-ms
- name: Build project
run: cube-ms build
- name: Run tests
run: npm test
```
## Troubleshooting
### Common Issues
1. **Command not found**
```bash
npm install -g cube-ms
# or use npx
npx cube-ms --version
```
2. **Port already in use**
```bash
cube-ms dev --port 8080
```
3. **Permission errors**
```bash
chmod +x ./bin/cube-ms.js
```
### Getting Help
```bash
cube-ms --help
cube-ms <command> --help
```
## Examples Repository
Check out example projects:
- [Basic Microservice](./Examples/basic-service/)
- [REST API](./Examples/rest-api/)
- [Authentication Service](./Examples/auth-service/)
## Contributing
Contribute to Cube-MS CLI:
1. Fork the repository
2. Create a feature branch
3. Add your improvements
4. Submit a pull request
## Support
- š [Documentation](./README.md)
- š [Issues](https://github.com/cube-ms/issues)
- š¬ [Discussions](https://github.com/cube-ms/discussions)