Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 17:56:18 +08:00
commit 56dc03d367
10 changed files with 1245 additions and 0 deletions

80
commands/api-scaffold.md Normal file
View File

@@ -0,0 +1,80 @@
# API Scaffolding Command
Generate production-ready backend API structure with authentication, database, and best practices.
## Task
You are an expert backend API architect. Generate a complete, production-ready API scaffold based on the user's technology stack preference.
### Steps:
1. **Detect or Ask for Stack**:
- Node.js (Express, NestJS, Fastify)
- Python (FastAPI, Django, Flask)
- .NET (ASP.NET Core)
2. **Generate Project Structure**:
```
src/
├── api/
│ ├── controllers/
│ ├── routes/
│ └── middleware/
├── core/
│ ├── config/
│ ├── database/
│ └── auth/
├── models/
├── services/
├── utils/
└── tests/
```
3. **Include Essential Components**:
- **Authentication**: JWT-based auth with refresh tokens
- **Database**: ORM setup (TypeORM, Sequelize, SQLAlchemy, Entity Framework)
- **Validation**: Request validation (Joi, Pydantic, FluentValidation)
- **Error Handling**: Global error handler
- **Logging**: Structured logging (Winston, Pino, Serilog)
- **Testing**: Unit and integration test setup
- **Docker**: Dockerfile and docker-compose.yml
- **Environment**: .env.example with all required variables
4. **Generate Configuration Files**:
- package.json / requirements.txt / .csproj
- tsconfig.json (TypeScript) / pyproject.toml (Python)
- .gitignore
- README.md with setup instructions
- .env.example
5. **Add Sample Endpoints**:
- GET /health (health check)
- POST /auth/register
- POST /auth/login
- POST /auth/refresh
- GET /users/me (protected)
- CRUD for a sample resource
6. **Best Practices**:
- Dependency injection
- Clean architecture separation
- Security headers (CORS, Helmet)
- Rate limiting
- API versioning
- OpenAPI/Swagger documentation
### Example Usage:
```
User: "Scaffold a NestJS API with PostgreSQL"
Result: Complete NestJS project with TypeORM, JWT auth, Swagger docs
```
```
User: "Create FastAPI backend with MongoDB"
Result: FastAPI project with Motor (async MongoDB), Pydantic models, JWT
```
### Output:
Generate all files with proper content, not just placeholders. Include comments explaining key configurations.

109
commands/crud-generate.md Normal file
View File

@@ -0,0 +1,109 @@
# CRUD Generator Command
Generate complete CRUD (Create, Read, Update, Delete) operations for a database entity.
## Task
You are an expert backend developer. Generate a complete CRUD implementation for a specified entity/model with:
### Required Information (Ask if not provided):
1. **Entity Name**: e.g., "User", "Product", "Order"
2. **Fields/Schema**: List of fields with types
3. **Stack**: Node.js/Python/.NET
4. **Framework**: Express/NestJS/FastAPI/Django/ASP.NET Core
5. **Database**: PostgreSQL/MySQL/MongoDB
### Generate:
#### 1. **Model/Entity**
```typescript
// Example for TypeORM
@Entity()
export class Product {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@Column('decimal', { precision: 10, scale: 2 })
price: number;
@Column({ type: 'text', nullable: true })
description: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
```
#### 2. **Repository/Data Access**
- Custom query methods
- Filtering, sorting, pagination
- Relationships (if applicable)
#### 3. **Service Layer**
```typescript
export class ProductService {
async create(dto: CreateProductDto): Promise<Product> { }
async findAll(query: QueryDto): Promise<PaginatedResponse<Product>> { }
async findById(id: string): Promise<Product> { }
async update(id: string, dto: UpdateProductDto): Promise<Product> { }
async delete(id: string): Promise<void> { }
}
```
#### 4. **DTOs (Data Transfer Objects)**
- CreateDto (input validation)
- UpdateDto (partial update)
- ResponseDto (output serialization)
- QueryDto (filtering/pagination)
#### 5. **Controller/Routes**
```typescript
// REST endpoints
POST /api/products - Create
GET /api/products - List (with pagination/filtering)
GET /api/products/:id - Get by ID
PUT /api/products/:id - Update
PATCH /api/products/:id - Partial update
DELETE /api/products/:id - Delete
```
#### 6. **Validation Rules**
- Required fields
- Type validation
- Custom business rules
- Unique constraints
#### 7. **Error Handling**
- Not found errors
- Validation errors
- Duplicate key errors
- Foreign key violations
#### 8. **Tests**
- Unit tests for service
- Integration tests for endpoints
- E2E tests with test database
### Best Practices:
- **Transactions**: Wrap complex operations in DB transactions
- **Soft Delete**: Add deletedAt column instead of hard delete
- **Audit Fields**: createdAt, updatedAt, createdBy, updatedBy
- **Pagination**: Cursor or offset-based
- **Filtering**: Support for common operators (eq, ne, gt, lt, like)
- **Relationships**: Handle related entities properly
- **Security**: Authorization checks, input sanitization
### Example:
```
User: "Generate CRUD for Product entity with name, price, description"
Result: Complete model, service, controller, DTOs, tests for Product
```

View File

@@ -0,0 +1,139 @@
# Database Migration Generator
Generate database migration files for schema changes.
## Task
You are an expert database migration specialist. Generate migration files based on the user's requirements.
### Required Information (Ask if not provided):
1. **Migration Type**:
- Create table
- Add column(s)
- Modify column(s)
- Drop column(s)
- Add index
- Add foreign key
- Seed data
2. **ORM/Tool**:
- TypeORM (Node.js)
- Sequelize (Node.js)
- Alembic (Python)
- Entity Framework (. NET)
- Flyway (Java)
- Raw SQL
3. **Database**: PostgreSQL, MySQL, MongoDB, SQL Server
### Generate Migration:
#### 1. **Up Migration** (Apply Changes)
```typescript
// TypeORM example
export class CreateProductsTable1234567890 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: 'products',
columns: [
{
name: 'id',
type: 'uuid',
isPrimary: true,
default: 'uuid_generate_v4()',
},
{
name: 'name',
type: 'varchar',
length: '255',
isNullable: false,
},
{
name: 'price',
type: 'decimal',
precision: 10,
scale: 2,
isNullable: false,
},
{
name: 'created_at',
type: 'timestamp',
default: 'now()',
},
],
}),
true
);
}
}
```
#### 2. **Down Migration** (Rollback)
```typescript
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('products');
}
```
#### 3. **Migration Naming**:
- Timestamp-based: `1234567890_create_products_table.ts`
- Descriptive: Clearly state what the migration does
#### 4. **Safety Checks**:
- Check if table/column exists before creating
- Use transactions for complex migrations
- Add indexes concurrently (PostgreSQL)
- Avoid locking production tables
#### 5. **Data Migrations**:
```typescript
// Example: Backfill existing data
await queryRunner.query(`
UPDATE users
SET status = 'active'
WHERE status IS NULL
`);
```
### Best Practices:
- **Idempotency**: Migrations should be safe to run multiple times
- **Atomicity**: Wrap in transactions where possible
- **Reversibility**: Always provide down migration
- **Testing**: Test both up and down on staging database
- **Documentation**: Add comments explaining complex logic
- **Performance**: Consider impact on large tables
- **Indexes**: Add indexes for foreign keys
### Common Patterns:
1. **Add Column with Default**:
```sql
ALTER TABLE users
ADD COLUMN email_verified BOOLEAN DEFAULT FALSE;
```
2. **Rename Column** (safe):
```sql
-- Step 1: Add new column
ALTER TABLE users ADD COLUMN full_name VARCHAR(255);
-- Step 2: Copy data
UPDATE users SET full_name = name;
-- Step 3: Drop old column (after deployment)
ALTER TABLE users DROP COLUMN name;
```
3. **Change Column Type**:
```sql
ALTER TABLE products
ALTER COLUMN price TYPE NUMERIC(12,2) USING price::numeric(12,2);
```
### Example:
```
User: "Create migration to add email_verified column to users table"
Result: Complete TypeORM migration with up/down, safe defaults
```