Add comprehensive skills and documentation for various technologies

This commit is contained in:
duthaho
2025-11-29 18:07:28 +07:00
commit ef96f165ef
60 changed files with 10538 additions and 0 deletions
+92
View File
@@ -0,0 +1,92 @@
# OpenAPI
## Description
OpenAPI/Swagger specification patterns for REST API documentation.
## When to Use
- Documenting REST APIs
- Generating API clients
- API design-first development
---
## Core Patterns
### Basic Specification
```yaml
openapi: 3.0.3
info:
title: My API
version: 1.0.0
paths:
/users:
get:
summary: List users
responses:
'200':
description: Success
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: string
email:
type: string
format: email
required:
- id
- email
```
### Request Body
```yaml
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUser'
example:
email: user@example.com
name: John
```
### Error Responses
```yaml
responses:
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
```
## Best Practices
1. Use $ref for reusable schemas
2. Include examples
3. Document all error responses
4. Use proper HTTP status codes
5. Add security schemes
## Common Pitfalls
- **Missing examples**: Add realistic examples
- **No error docs**: Document all errors
- **Inconsistent naming**: Use consistent conventions
+73
View File
@@ -0,0 +1,73 @@
# MongoDB
## Description
MongoDB patterns including document design, queries, and aggregation.
## When to Use
- MongoDB database operations
- Document-based data modeling
- Aggregation pipelines
---
## Core Patterns
### Document Operations
```javascript
// Insert
db.users.insertOne({
email: 'user@example.com',
name: 'John',
createdAt: new Date()
});
// Find
db.users.find({ active: true }).sort({ createdAt: -1 }).limit(20);
// Update
db.users.updateOne(
{ _id: ObjectId('...') },
{ $set: { name: 'Jane' } }
);
```
### Aggregation
```javascript
db.orders.aggregate([
{ $match: { status: 'completed' } },
{ $group: {
_id: '$userId',
totalSpent: { $sum: '$amount' },
orderCount: { $count: {} }
}},
{ $sort: { totalSpent: -1 } }
]);
```
### Indexes
```javascript
// Single field
db.users.createIndex({ email: 1 }, { unique: true });
// Compound
db.posts.createIndex({ userId: 1, createdAt: -1 });
```
## Best Practices
1. Embed frequently accessed data
2. Use references for large/independent data
3. Create indexes for query patterns
4. Use aggregation for complex queries
5. Avoid unbounded arrays
## Common Pitfalls
- **Unbounded arrays**: Limit array size
- **Missing indexes**: Analyze query patterns
- **Over-embedding**: Consider data access patterns
@@ -0,0 +1,69 @@
# PostgreSQL
## Description
PostgreSQL database patterns including queries, indexing, and optimization.
## When to Use
- PostgreSQL database operations
- SQL query optimization
- Schema design
---
## Core Patterns
### Basic Queries
```sql
-- Select with filtering
SELECT id, name, email
FROM users
WHERE active = true
ORDER BY created_at DESC
LIMIT 20 OFFSET 0;
-- Join
SELECT u.*, COUNT(p.id) as post_count
FROM users u
LEFT JOIN posts p ON p.user_id = u.id
GROUP BY u.id;
```
### Indexes
```sql
-- Single column index
CREATE INDEX idx_users_email ON users(email);
-- Composite index
CREATE INDEX idx_posts_user_date ON posts(user_id, created_at DESC);
-- Partial index
CREATE INDEX idx_active_users ON users(email) WHERE active = true;
```
### Migrations
```sql
-- Add column with default
ALTER TABLE users ADD COLUMN role VARCHAR(50) DEFAULT 'user';
-- Add constraint
ALTER TABLE users ADD CONSTRAINT unique_email UNIQUE (email);
```
## Best Practices
1. Use indexes for filtered/sorted columns
2. Use EXPLAIN ANALYZE for slow queries
3. Avoid SELECT * in production
4. Use transactions for multiple operations
5. Use connection pooling
## Common Pitfalls
- **N+1 queries**: Use JOINs or batch loading
- **Missing indexes**: Add indexes for WHERE/ORDER BY
- **Large transactions**: Keep transactions short
+94
View File
@@ -0,0 +1,94 @@
# Docker
## Description
Docker containerization including Dockerfiles, compose, and best practices.
## When to Use
- Containerizing applications
- Local development environments
- CI/CD pipelines
---
## Core Patterns
### Multi-stage Dockerfile (Node.js)
```dockerfile
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/index.js"]
```
### Python Dockerfile
```dockerfile
FROM python:3.12-slim
WORKDIR /app
# Install dependencies first (caching)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0"]
```
### Docker Compose
```yaml
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgresql://user:pass@db:5432/app
depends_on:
- db
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: app
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
```
## Best Practices
1. Use multi-stage builds
2. Order commands for cache efficiency
3. Use .dockerignore
4. Run as non-root user
5. Use specific image tags
## Common Pitfalls
- **Large images**: Use slim/alpine bases
- **Cache busting**: Order COPY commands properly
- **Root user**: Add USER instruction
@@ -0,0 +1,88 @@
# GitHub Actions
## Description
GitHub Actions CI/CD workflows including testing, building, and deployment.
## When to Use
- Setting up CI/CD pipelines
- Automating tests and builds
- Deployment automation
---
## Core Patterns
### Basic CI Workflow
```yaml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test
```
### Matrix Builds
```yaml
jobs:
test:
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
node: [18, 20]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
```
### Caching
```yaml
- uses: actions/cache@v4
with:
path: ~/.npm
key: npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: npm-
```
### Secrets
```yaml
- name: Deploy
env:
API_KEY: ${{ secrets.API_KEY }}
run: deploy --key "$API_KEY"
```
## Best Practices
1. Use caching for dependencies
2. Run jobs in parallel when possible
3. Use environment secrets
4. Pin action versions
5. Add proper triggers
## Common Pitfalls
- **Slow pipelines**: Add caching
- **Secret exposure**: Never echo secrets
- **Unpinned versions**: Use @v4 not @main
+91
View File
@@ -0,0 +1,91 @@
# Django
## Description
Django web framework with ORM, views, and REST framework patterns.
## When to Use
- Python web applications
- Admin interfaces
- Django REST Framework APIs
---
## Core Patterns
### Models
```python
from django.db import models
class User(models.Model):
email = models.EmailField(unique=True)
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.email
```
### Views (Class-based)
```python
from django.views.generic import ListView, DetailView
class UserListView(ListView):
model = User
template_name = 'users/list.html'
context_object_name = 'users'
paginate_by = 20
class UserDetailView(DetailView):
model = User
template_name = 'users/detail.html'
```
### Django REST Framework
```python
from rest_framework import serializers, viewsets
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'email', 'name', 'created_at']
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
```
### URLs
```python
from django.urls import path, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('users', UserViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
```
## Best Practices
1. Use class-based views for standard CRUD
2. Define model methods for business logic
3. Use serializers for validation
4. Add proper permissions
5. Use select_related/prefetch_related for queries
## Common Pitfalls
- **N+1 queries**: Use select_related/prefetch_related
- **Missing migrations**: Run makemigrations
- **No validation**: Use serializers properly
@@ -0,0 +1,89 @@
# FastAPI
## Description
FastAPI web framework with async patterns, Pydantic validation, and OpenAPI documentation.
## When to Use
- Building REST APIs with Python
- Async web applications
- OpenAPI/Swagger documentation needed
---
## Core Patterns
### Route Definition
```python
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
app = FastAPI()
class UserCreate(BaseModel):
email: str
name: str
class UserResponse(BaseModel):
id: int
email: str
name: str
@app.post("/users", response_model=UserResponse, status_code=201)
async def create_user(user: UserCreate):
# Create user logic
return UserResponse(id=1, **user.model_dump())
@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int):
user = await get_user_by_id(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
```
### Dependency Injection
```python
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with async_session_maker() as session:
yield session
@app.get("/users")
async def list_users(db: AsyncSession = Depends(get_db)):
return await db.execute(select(User))
```
### Router Organization
```python
from fastapi import APIRouter
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/")
async def list_users():
pass
# In main.py
app.include_router(router)
```
## Best Practices
1. Use Pydantic models for request/response validation
2. Organize routes with APIRouter
3. Use dependency injection for services
4. Return proper HTTP status codes
5. Add OpenAPI descriptions
## Common Pitfalls
- **Blocking I/O in async**: Use async libraries
- **Missing response models**: Always define them
- **No error handling**: Use HTTPException properly
+112
View File
@@ -0,0 +1,112 @@
# Next.js
## Description
Next.js framework with App Router, Server Components, and full-stack development patterns.
## When to Use
- React applications with SSR/SSG
- Full-stack applications
- App Router patterns
---
## Core Patterns
### App Router Structure
```
app/
├── layout.tsx # Root layout
├── page.tsx # Home page
├── loading.tsx # Loading UI
├── error.tsx # Error UI
├── api/
│ └── users/
│ └── route.ts # API route
└── users/
├── page.tsx # Users page
└── [id]/
└── page.tsx # User detail
```
### Server Components
```tsx
// app/users/page.tsx - Server Component (default)
async function UsersPage() {
const users = await db.users.findMany();
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
```
### Client Components
```tsx
'use client';
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
);
}
```
### API Routes
```typescript
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET() {
const users = await db.users.findMany();
return NextResponse.json(users);
}
export async function POST(request: NextRequest) {
const data = await request.json();
const user = await db.users.create({ data });
return NextResponse.json(user, { status: 201 });
}
```
### Server Actions
```tsx
// app/actions.ts
'use server';
export async function createUser(formData: FormData) {
const name = formData.get('name') as string;
await db.users.create({ data: { name } });
revalidatePath('/users');
}
```
## Best Practices
1. Use Server Components by default
2. Add 'use client' only when needed
3. Colocate data fetching with components
4. Use loading.tsx for suspense boundaries
5. Implement proper error boundaries
## Common Pitfalls
- **Using hooks in Server Components**: Mark as 'use client'
- **Large client bundles**: Keep client components small
- **Missing loading states**: Add loading.tsx files
+108
View File
@@ -0,0 +1,108 @@
# React
## Description
React component patterns, hooks, and state management best practices.
## When to Use
- Building React components
- Using React hooks
- Component state management
---
## Core Patterns
### Functional Components
```tsx
interface UserCardProps {
user: User;
onSelect?: (user: User) => void;
}
export function UserCard({ user, onSelect }: UserCardProps) {
return (
<div className="card" onClick={() => onSelect?.(user)}>
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
);
}
```
### Hooks
```tsx
// useState
const [count, setCount] = useState(0);
// useEffect
useEffect(() => {
const subscription = subscribe();
return () => subscription.unsubscribe();
}, [dependency]);
// useMemo
const expensive = useMemo(() => compute(data), [data]);
// useCallback
const handleClick = useCallback(() => {
doSomething(id);
}, [id]);
```
### Custom Hooks
```tsx
function useUser(id: string) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
fetchUser(id)
.then(setUser)
.finally(() => setLoading(false));
}, [id]);
return { user, loading };
}
```
### Context Pattern
```tsx
const UserContext = createContext<User | null>(null);
export function UserProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
return (
<UserContext.Provider value={user}>
{children}
</UserContext.Provider>
);
}
export function useUser() {
const context = useContext(UserContext);
if (!context) throw new Error('useUser must be within UserProvider');
return context;
}
```
## Best Practices
1. Keep components small and focused
2. Use TypeScript for props
3. Memoize expensive computations
4. Clean up effects properly
5. Lift state up when needed
## Common Pitfalls
- **Missing dependencies in hooks**: Include all dependencies
- **State updates on unmounted**: Use cleanup functions
- **Prop drilling**: Use context or composition
@@ -0,0 +1,87 @@
# shadcn/ui
## Description
shadcn/ui component library patterns with Radix primitives and Tailwind styling.
## When to Use
- Building React component libraries
- Accessible UI components
- Customizable design systems
---
## Core Patterns
### Button Component
```tsx
import { Button } from "@/components/ui/button"
<Button variant="default">Primary</Button>
<Button variant="secondary">Secondary</Button>
<Button variant="outline">Outline</Button>
<Button variant="ghost">Ghost</Button>
<Button variant="destructive">Destructive</Button>
```
### Form with Validation
```tsx
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Form, FormField, FormItem, FormLabel, FormControl } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
const form = useForm({
resolver: zodResolver(schema),
});
<Form {...form}>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
</FormItem>
)}
/>
</Form>
```
### Dialog
```tsx
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
<Dialog>
<DialogTrigger asChild>
<Button>Open</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Title</DialogTitle>
</DialogHeader>
Content
</DialogContent>
</Dialog>
```
## Best Practices
1. Use cn() for conditional classes
2. Compose primitives for custom components
3. Follow accessibility patterns
4. Customize via CSS variables
5. Use asChild for composition
## Common Pitfalls
- **Missing cn import**: Import from lib/utils
- **Wrong composition**: Use asChild properly
- **Hardcoded colors**: Use CSS variables
+82
View File
@@ -0,0 +1,82 @@
# Tailwind CSS
## Description
Tailwind CSS utility-first styling with responsive design and component patterns.
## When to Use
- Styling React/Next.js components
- Responsive design
- Rapid UI development
---
## Core Patterns
### Layout
```html
<!-- Flexbox -->
<div class="flex items-center justify-between gap-4">
<div>Left</div>
<div>Right</div>
</div>
<!-- Grid -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div>Item</div>
</div>
<!-- Container -->
<div class="container mx-auto px-4">
Content
</div>
```
### Responsive
```html
<!-- Mobile-first breakpoints -->
<div class="w-full md:w-1/2 lg:w-1/3">
<!-- sm: 640px, md: 768px, lg: 1024px, xl: 1280px -->
</div>
<h1 class="text-xl md:text-2xl lg:text-4xl">
Responsive text
</h1>
```
### States
```html
<button class="
bg-blue-500 hover:bg-blue-600
focus:ring-2 focus:ring-blue-500 focus:ring-offset-2
disabled:opacity-50 disabled:cursor-not-allowed
">
Button
</button>
```
### Dark Mode
```html
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
Content
</div>
```
## Best Practices
1. Use consistent spacing scale
2. Mobile-first design
3. Extract repeated patterns to components
4. Use @apply sparingly
5. Leverage dark mode utilities
## Common Pitfalls
- **Too many classes**: Extract to components
- **Inconsistent spacing**: Stick to scale
- **Missing responsive**: Test all breakpoints
@@ -0,0 +1,101 @@
# JavaScript
## Description
Modern JavaScript (ES6+) patterns and best practices for Node.js and browser environments.
## When to Use
- Working with JavaScript files (.js, .mjs)
- Browser scripting
- Node.js applications without TypeScript
---
## Core Patterns
### Modern Syntax
```javascript
// Destructuring
const { name, email } = user;
const [first, ...rest] = items;
// Spread operator
const merged = { ...defaults, ...options };
const combined = [...array1, ...array2];
// Template literals
const message = `Hello, ${name}!`;
// Optional chaining and nullish coalescing
const city = user?.address?.city ?? 'Unknown';
```
### Async Patterns
```javascript
// Async/await
async function fetchData(url) {
const response = await fetch(url);
if (!response.ok) throw new Error('Fetch failed');
return response.json();
}
// Promise.all for parallel
const results = await Promise.all([
fetchData(url1),
fetchData(url2),
]);
// Error handling
try {
const data = await fetchData(url);
} catch (error) {
console.error('Failed:', error.message);
}
```
### Array Methods
```javascript
// Map, filter, reduce
const names = users.map(u => u.name);
const active = users.filter(u => u.active);
const total = items.reduce((sum, i) => sum + i.price, 0);
// Find and includes
const user = users.find(u => u.id === id);
const hasAdmin = users.some(u => u.role === 'admin');
```
### Classes
```javascript
class UserService {
#db; // Private field
constructor(database) {
this.#db = database;
}
async findById(id) {
return this.#db.users.find(u => u.id === id);
}
}
```
## Best Practices
1. Use `const` by default, `let` when needed
2. Avoid `var` - use block-scoped declarations
3. Use arrow functions for callbacks
4. Handle all promise rejections
5. Use ESLint for consistent style
## Common Pitfalls
- **Implicit type coercion**: Use `===` instead of `==`
- **Callback hell**: Use async/await
- **Mutating objects**: Create new objects with spread
- **Not handling errors**: Always catch promise rejections
+110
View File
@@ -0,0 +1,110 @@
# Python
## Description
Python development expertise including type hints, async patterns, virtual environments, and Pythonic idioms.
## When to Use
- Working with Python files (.py)
- Writing Python scripts or applications
- Using Python frameworks (Django, FastAPI, Flask)
- Data processing and automation
---
## Core Patterns
### Type Hints
```python
from typing import Optional, List, Dict, Union
from collections.abc import Callable
def process_items(
items: List[str],
callback: Callable[[str], None],
config: Optional[Dict[str, Any]] = None
) -> List[str]:
"""Process items with optional callback."""
return [callback(item) for item in items]
```
### Async/Await
```python
import asyncio
from typing import List
async def fetch_data(url: str) -> dict:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()
async def fetch_all(urls: List[str]) -> List[dict]:
return await asyncio.gather(*[fetch_data(url) for url in urls])
```
### Context Managers
```python
from contextlib import contextmanager
@contextmanager
def managed_resource():
resource = acquire_resource()
try:
yield resource
finally:
release_resource(resource)
# Usage
with managed_resource() as r:
r.do_something()
```
### Dataclasses
```python
from dataclasses import dataclass, field
from datetime import datetime
@dataclass
class User:
id: int
email: str
name: str
created_at: datetime = field(default_factory=datetime.now)
def __post_init__(self):
self.email = self.email.lower()
```
### Pydantic Models
```python
from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel):
email: EmailStr
name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=8)
class Config:
str_strip_whitespace = True
```
## Best Practices
1. Use type hints for all public functions
2. Use dataclasses or Pydantic for data models
3. Prefer context managers for resource management
4. Use async for I/O-bound operations
5. Follow PEP 8 style guidelines
## Common Pitfalls
- **Mutable default arguments**: Use `None` and initialize in function
- **Not closing resources**: Use `with` statements
- **Blocking in async**: Use `asyncio.to_thread()` for CPU work
- **Catching bare exceptions**: Be specific with exception types
@@ -0,0 +1,128 @@
# TypeScript
## Description
TypeScript development with strict typing, advanced type utilities, and modern patterns.
## When to Use
- Working with TypeScript files (.ts, .tsx)
- Building typed JavaScript applications
- React/Next.js development
- Node.js backend development
---
## Core Patterns
### Type Definitions
```typescript
// Interfaces for objects
interface User {
id: string;
email: string;
name: string;
createdAt: Date;
}
// Types for unions and utilities
type Status = 'pending' | 'active' | 'inactive';
type UserWithStatus = User & { status: Status };
// Generic types
type ApiResponse<T> = {
data: T;
error?: string;
status: number;
};
```
### Utility Types
```typescript
// Partial - all properties optional
type UserUpdate = Partial<User>;
// Pick - select properties
type UserPreview = Pick<User, 'id' | 'name'>;
// Omit - exclude properties
type UserWithoutId = Omit<User, 'id'>;
// Record - dictionary type
type UserMap = Record<string, User>;
```
### Async Patterns
```typescript
async function fetchUser(id: string): Promise<User> {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`Failed to fetch user: ${response.status}`);
}
return response.json();
}
// Error handling
async function safeOperation<T>(
operation: () => Promise<T>
): Promise<[T, null] | [null, Error]> {
try {
const result = await operation();
return [result, null];
} catch (error) {
return [null, error as Error];
}
}
```
### Class Patterns
```typescript
class UserService {
constructor(private readonly db: Database) {}
async findById(id: string): Promise<User | null> {
return this.db.users.findUnique({ where: { id } });
}
async create(data: UserCreate): Promise<User> {
return this.db.users.create({ data });
}
}
```
### Zod Validation
```typescript
import { z } from 'zod';
const UserSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
password: z.string().min(8),
});
type UserInput = z.infer<typeof UserSchema>;
function validateUser(data: unknown): UserInput {
return UserSchema.parse(data);
}
```
## Best Practices
1. Enable strict mode in tsconfig.json
2. Avoid `any` - use `unknown` and type guards
3. Use interfaces for object shapes, types for unions
4. Prefer `const` assertions for literal types
5. Use discriminated unions for state
## Common Pitfalls
- **Using `any`**: Defeats type safety
- **Not handling null/undefined**: Use strict null checks
- **Type assertions**: Prefer type guards
- **Ignoring errors**: Handle all promise rejections
+74
View File
@@ -0,0 +1,74 @@
# OWASP Security
## Description
OWASP Top 10 security practices and secure coding patterns.
## When to Use
- Security code reviews
- Implementing authentication
- Handling user input
---
## Core Patterns
### Input Validation
```python
# Always validate and sanitize
from pydantic import BaseModel, EmailStr
class UserInput(BaseModel):
email: EmailStr
name: str = Field(min_length=1, max_length=100)
```
### SQL Injection Prevention
```python
# Never concatenate user input
# Bad
query = f"SELECT * FROM users WHERE id = {user_id}"
# Good - parameterized
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
```
### XSS Prevention
```typescript
// Never use innerHTML with user data
// Bad
element.innerHTML = userInput;
// Good
element.textContent = userInput;
```
### Authentication
```python
# Hash passwords properly
from passlib.hash import argon2
hashed = argon2.hash(password)
verified = argon2.verify(password, hashed)
```
## Security Checklist
- [ ] Input validation on all user data
- [ ] Parameterized queries
- [ ] Output encoding
- [ ] Strong password hashing
- [ ] Secure session management
- [ ] HTTPS everywhere
- [ ] Security headers configured
## Common Pitfalls
- **Trusting user input**: Always validate
- **SQL concatenation**: Use parameters
- **Storing plain passwords**: Use argon2/bcrypt
+90
View File
@@ -0,0 +1,90 @@
# pytest
## Description
Python testing with pytest including fixtures, parametrization, and mocking.
## When to Use
- Writing Python tests
- Test fixtures and setup
- Mocking dependencies
---
## Core Patterns
### Basic Tests
```python
import pytest
def test_addition():
assert 1 + 1 == 2
def test_exception():
with pytest.raises(ValueError, match="Invalid"):
raise ValueError("Invalid input")
```
### Fixtures
```python
@pytest.fixture
def user():
return User(id=1, name="Test")
@pytest.fixture
def db_session():
session = create_session()
yield session
session.close()
def test_with_fixtures(user, db_session):
db_session.add(user)
assert user.id is not None
```
### Parametrization
```python
@pytest.mark.parametrize("input,expected", [
("hello", "HELLO"),
("world", "WORLD"),
("", ""),
])
def test_uppercase(input, expected):
assert input.upper() == expected
```
### Mocking
```python
from unittest.mock import Mock, patch
def test_with_mock():
service = Mock()
service.get_user.return_value = {"id": 1}
result = service.get_user(1)
assert result["id"] == 1
@patch('module.external_api')
def test_with_patch(mock_api):
mock_api.fetch.return_value = {"data": []}
# Test code that uses external_api
```
## Best Practices
1. Use fixtures for test setup
2. Parametrize for multiple test cases
3. Mock external dependencies
4. Use descriptive test names
5. Keep tests independent
## Common Pitfalls
- **Shared state**: Use fresh fixtures
- **Over-mocking**: Only mock boundaries
- **Slow tests**: Use markers for slow tests
+89
View File
@@ -0,0 +1,89 @@
# Vitest
## Description
Modern JavaScript/TypeScript testing with Vitest including mocking and coverage.
## When to Use
- Testing JavaScript/TypeScript
- React component testing
- Unit and integration tests
---
## Core Patterns
### Basic Tests
```typescript
import { describe, it, expect } from 'vitest';
describe('math', () => {
it('should add numbers', () => {
expect(1 + 1).toBe(2);
});
it('should throw on invalid input', () => {
expect(() => divide(1, 0)).toThrow('Division by zero');
});
});
```
### Mocking
```typescript
import { vi, describe, it, expect } from 'vitest';
// Mock module
vi.mock('./api', () => ({
fetchUser: vi.fn().mockResolvedValue({ id: 1 })
}));
// Mock function
const callback = vi.fn();
callback('arg');
expect(callback).toHaveBeenCalledWith('arg');
```
### Async Tests
```typescript
it('should fetch data', async () => {
const data = await fetchData();
expect(data).toEqual({ id: 1 });
});
it('should reject on error', async () => {
await expect(fetchData()).rejects.toThrow('Error');
});
```
### React Testing
```typescript
import { render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
it('should handle click', async () => {
const onClick = vi.fn();
render(<Button onClick={onClick}>Click</Button>);
await userEvent.click(screen.getByRole('button'));
expect(onClick).toHaveBeenCalled();
});
```
## Best Practices
1. Use describe blocks for grouping
2. Prefer async/await for async tests
3. Use userEvent over fireEvent
4. Mock at module boundaries
5. Clean up after tests
## Common Pitfalls
- **Not awaiting async**: Always await promises
- **Stale mocks**: Clear mocks between tests
- **Testing implementation**: Test behavior