Git Commit with Claude
bashCommit changes with a well-formatted message following conventional commits
gitcommitconventional
# Stage all changes
git add .
# Commit with conventional format
git commit -m "feat: add user authentication
- Implement JWT token generation
- Add password hashing with bcrypt
- Create login/logout endpoints
Co-authored-by: Claude <claude@anthropic.com>"Pandas DataFrame Operations
pythonCommon pandas operations for data cleaning and transformation
pythonpandasdata
import pandas as pd
# Read data
df = pd.read_csv('data.csv')
# Basic cleaning
df = (df
.dropna(subset=['important_column'])
.drop_duplicates()
.rename(columns={'old_name': 'new_name'})
.assign(
new_column=lambda x: x['col1'] + x['col2'],
date=lambda x: pd.to_datetime(x['date_string'])
)
.query('value > 0')
)
# Group and aggregate
summary = (df
.groupby('category')
.agg({
'value': ['sum', 'mean', 'count'],
'date': 'max'
})
.reset_index()
)Custom React Hook
typescriptTemplate for creating a custom React hook with TypeScript
reacttypescripthooks
import { useState, useEffect, useCallback } from 'react'
interface UseAsyncOptions<T> {
immediate?: boolean
onSuccess?: (data: T) => void
onError?: (error: Error) => void
}
function useAsync<T>(
asyncFunction: () => Promise<T>,
options: UseAsyncOptions<T> = {}
) {
const { immediate = true, onSuccess, onError } = options
const [data, setData] = useState<T | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<Error | null>(null)
const execute = useCallback(async () => {
setLoading(true)
setError(null)
try {
const result = await asyncFunction()
setData(result)
onSuccess?.(result)
return result
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err))
setError(error)
onError?.(error)
throw error
} finally {
setLoading(false)
}
}, [asyncFunction, onSuccess, onError])
useEffect(() => {
if (immediate) {
execute()
}
}, [execute, immediate])
return { data, loading, error, execute }
}
export default useAsyncExpress Error Middleware
typescriptGlobal error handling middleware for Express.js
expresstypescripterror-handling
import { Request, Response, NextFunction } from 'express'
// Custom error class
class AppError extends Error {
constructor(
public statusCode: number,
public message: string,
public isOperational = true
) {
super(message)
Object.setPrototypeOf(this, AppError.prototype)
}
}
// Error handler middleware
const errorHandler = (
err: Error,
req: Request,
res: Response,
next: NextFunction
) => {
if (err instanceof AppError) {
return res.status(err.statusCode).json({
status: 'error',
message: err.message,
})
}
// Log unexpected errors
console.error('Unexpected error:', err)
// Don't leak error details in production
const message = process.env.NODE_ENV === 'production'
? 'Internal server error'
: err.message
return res.status(500).json({
status: 'error',
message,
})
}
export { AppError, errorHandler }SQL Query Patterns
sqlCommon SQL query patterns for database operations
sqlpostgresdatabase
-- Get aggregated data with window functions
SELECT
user_id,
order_date,
amount,
SUM(amount) OVER (
PARTITION BY user_id
ORDER BY order_date
) as running_total,
AVG(amount) OVER (
PARTITION BY user_id
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) as moving_avg_7d
FROM orders
WHERE order_date >= CURRENT_DATE - INTERVAL '30 days';
-- Upsert pattern
INSERT INTO users (email, name, updated_at)
VALUES ('user@example.com', 'John', NOW())
ON CONFLICT (email)
DO UPDATE SET
name = EXCLUDED.name,
updated_at = NOW();
-- CTE for complex queries
WITH active_users AS (
SELECT user_id, COUNT(*) as session_count
FROM sessions
WHERE created_at >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY user_id
HAVING COUNT(*) >= 3
)
SELECT u.*, a.session_count
FROM users u
JOIN active_users a ON u.id = a.user_id;TypeScript Utility Types
typescriptUseful TypeScript utility types for better type safety
typescripttypesutility
// Make specific keys required
type RequireKeys<T, K extends keyof T> = T & Required<Pick<T, K>>
// Make specific keys optional
type OptionalKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
// Deep partial
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]
}
// Extract function return type
type AsyncReturnType<T extends (...args: any) => Promise<any>> =
T extends (...args: any) => Promise<infer R> ? R : never
// Type-safe object keys
function typedKeys<T extends object>(obj: T): (keyof T)[] {
return Object.keys(obj) as (keyof T)[]
}
// Type guard example
function isNotNull<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined
}
// Usage
const items = [1, null, 2, undefined, 3].filter(isNotNull)
// items is number[]Type-Safe API Fetch
typescriptA type-safe fetch wrapper with error handling
typescriptfetchapi
interface ApiResponse<T> {
data: T
status: number
}
interface ApiError {
message: string
status: number
}
async function apiFetch<T>(
url: string,
options?: RequestInit
): Promise<ApiResponse<T>> {
const response = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
...options?.headers,
},
})
const data = await response.json()
if (!response.ok) {
const error: ApiError = {
message: data.message || 'Request failed',
status: response.status,
}
throw error
}
return {
data,
status: response.status,
}
}
// Usage
interface User {
id: number
name: string
email: string
}
const { data: user } = await apiFetch<User>('/api/users/1')
// user is typed as UserEnvironment Variable Validation
typescriptType-safe environment variable validation with Zod
typescriptzodenv
import { z } from 'zod'
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'production', 'test']),
PORT: z.string().transform(Number).default('3000'),
DATABASE_URL: z.string().url(),
API_KEY: z.string().min(1),
ENABLE_CACHE: z.string().transform(v => v === 'true').default('false'),
})
// Parse and validate
const env = envSchema.parse(process.env)
// Export typed environment
export type Env = z.infer<typeof envSchema>
export { env }
// Usage
console.log(env.PORT) // number
console.log(env.ENABLE_CACHE) // boolean