Skip to main content

Functions & Templates in claude-setup

The claude-setup framework provides a comprehensive library of reusable functions and templates for common development patterns.

Core Functions

Project Initialization

// Initialize new project with best practices
createProject({
name: 'my-app',
type: 'fullstack',
framework: 'next',
database: 'postgresql',
auth: 'jwt',
testing: 'jest'
});

Code Generation

// Generate CRUD operations
generateCRUD({
entity: 'User',
fields: ['name', 'email', 'role'],
database: 'prisma',
validation: 'zod'
});

// Generate API endpoints
generateAPI({
entity: 'Product',
operations: ['create', 'read', 'update', 'delete'],
auth: true,
rateLimit: true
});

Testing Utilities

// Generate test suites
createTestSuite({
component: 'UserService',
type: 'unit',
coverage: 90,
mocks: ['database', 'email']
});

// Create integration tests
createIntegrationTests({
endpoints: ['/api/users', '/api/auth'],
scenarios: ['happy-path', 'error-cases'],
database: 'test-db'
});

Project Templates

Full-Stack Application

claude-setup new --template=fullstack
├── frontend/ # React/Next.js frontend
│ ├── components/ # Reusable UI components
│ ├── pages/ # Route components
│ ├── hooks/ # Custom React hooks
│ └── utils/ # Frontend utilities
├── backend/ # Node.js/Express backend
│ ├── controllers/ # Request handlers
│ ├── services/ # Business logic
│ ├── models/ # Data models
│ └── middleware/ # Express middleware
├── database/ # Database schema and migrations
├── tests/ # Test suites
└── docker/ # Containerization

Microservices Architecture

claude-setup new --template=microservices
├── services/
│ ├── auth-service/ # Authentication & authorization
│ ├── user-service/ # User management
│ ├── payment-service/ # Payment processing
│ └── notification-service/ # Notifications
├── shared/
│ ├── types/ # Shared TypeScript types
│ ├── utils/ # Common utilities
│ └── config/ # Shared configuration
├── gateway/ # API Gateway
├── infrastructure/ # Docker, K8s configs
└── monitoring/ # Logging, metrics

Component Library

claude-setup new --template=component-lib
├── src/
│ ├── components/ # React components
│ │ ├── Button/
│ │ ├── Input/
│ │ ├── Modal/
│ │ └── Layout/
│ ├── hooks/ # Custom hooks
│ ├── utils/ # Utility functions
│ └── types/ # TypeScript definitions
├── stories/ # Storybook stories
├── tests/ # Component tests
└── docs/ # Component documentation

Function Categories

Database Functions

// Schema generation
createSchema({
entities: ['User', 'Product', 'Order'],
relationships: ['one-to-many', 'many-to-many'],
indexes: ['email', 'created_at']
});

// Migration utilities
createMigration({
name: 'add-user-roles',
operations: ['add-column', 'create-index'],
rollback: true
});

// Seeding functions
createSeeder({
entity: 'User',
count: 100,
factory: 'realistic-data'
});

Authentication Functions

// JWT authentication setup
setupJWTAuth({
secret: 'env:JWT_SECRET',
expiry: '24h',
refresh: true,
roles: ['admin', 'user']
});

// OAuth integration
setupOAuth({
providers: ['google', 'github'],
scopes: ['email', 'profile'],
redirects: ['/dashboard']
});

// Role-based access control
setupRBAC({
roles: {
admin: ['read', 'write', 'delete'],
user: ['read', 'write'],
guest: ['read']
}
});

API Functions

// REST API generation
createRESTAPI({
entities: ['User', 'Product'],
middleware: ['auth', 'validation', 'rateLimit'],
documentation: 'openapi'
});

// GraphQL setup
setupGraphQL({
schema: 'code-first',
resolvers: 'auto-generate',
subscriptions: true
});

// Validation schemas
createValidation({
library: 'zod',
entities: ['User', 'Product'],
strict: true
});

Advanced Templates

E-commerce Platform

Complete e-commerce solution with:

  • Product catalog management
  • Shopping cart functionality
  • Payment processing (Stripe)
  • Order management
  • User authentication
  • Admin dashboard
  • Email notifications

SaaS Application

Multi-tenant SaaS template featuring:

  • Tenant isolation
  • Subscription management
  • Usage tracking
  • Role-based permissions
  • API rate limiting
  • Analytics dashboard
  • Billing integration

Real-time Chat Application

WebSocket-based chat platform with:

  • Real-time messaging
  • User presence
  • File sharing
  • Message history
  • Push notifications
  • Moderation tools
  • Voice/video calling

Template Customization

Configuration Options

// Customize template generation
claude-setup new --template=fullstack --config=custom.json

// custom.json
{
"database": "postgresql",
"auth": "firebase",
"styling": "tailwind",
"testing": "vitest",
"deployment": "vercel",
"features": ["real-time", "payments", "analytics"]
}

Template Inheritance

// Extend existing templates
createTemplate({
extends: 'fullstack',
name: 'my-custom-template',
additions: {
blockchain: 'ethereum',
ai: 'openai',
payments: 'crypto'
}
});

Function Composition

Workflow Functions

// Combine functions for complex workflows
const deploymentWorkflow = compose([
buildProject,
runTests,
dockerBuild,
pushToRegistry,
deployToK8s,
runSmokeTests
]);

// Error handling in workflows
const robustWorkflow = withErrorHandling([
buildProject,
runTests,
deploy
], {
retries: 3,
fallback: rollbackDeployment
});

Utility Functions

// File manipulation
createFile({
path: 'src/components/Button.tsx',
template: 'react-component',
props: { name: 'Button', typescript: true }
});

// Environment setup
setupEnvironment({
variables: ['DATABASE_URL', 'JWT_SECRET'],
files: ['.env.local', '.env.production'],
validation: true
});

// Dependency management
addDependencies({
production: ['express', 'prisma'],
development: ['jest', 'typescript'],
global: ['claude-setup']
});

Template Variables

Dynamic Content

// Template with variables
const componentTemplate = `
import React from 'react';

interface {{componentName}}Props {
{{#each props}}
{{name}}: {{type}};
{{/each}}
}

export const {{componentName}}: React.FC<{{componentName}}Props> = ({
{{#each props}}{{name}}{{#unless @last}}, {{/unless}}{{/each}}
}) => {
return (
<div className="{{kebabCase componentName}}">
{{content}}
</div>
);
};
`;

Template Helpers

// Built-in helpers
{
camelCase: 'userProfile',
pascalCase: 'UserProfile',
kebabCase: 'user-profile',
snakeCase: 'user_profile',
pluralize: 'users',
timestamp: '2024-01-01T00:00:00Z'
}

Testing Templates

Unit Test Templates

// Jest unit test template
createUnitTest({
target: 'UserService',
methods: ['create', 'update', 'delete'],
mocks: ['database', 'email'],
coverage: 95
});

Integration Test Templates

// API integration test template  
createAPITest({
endpoints: ['/api/users'],
scenarios: ['crud-operations', 'validation', 'auth'],
database: 'test-container'
});

E2E Test Templates

// Playwright E2E test template
createE2ETest({
flows: ['user-registration', 'purchase-flow'],
browsers: ['chromium', 'firefox'],
devices: ['desktop', 'mobile']
});

Best Practices

1. Template Selection

Choose templates based on project requirements:

  • Simple projects: Use minimal templates
  • Enterprise apps: Use comprehensive templates
  • Learning projects: Use educational templates

2. Function Composition

Break complex operations into composable functions:

// Good: Composable functions
const result = pipe(
validateInput,
transformData,
saveToDatabase,
sendNotification
)(inputData);

// Avoid: Monolithic functions
const doEverything = (input) => { /* 200 lines */ };

3. Template Customization

Always customize templates for your specific needs:

  • Remove unused features
  • Add project-specific requirements
  • Configure for your tech stack

4. Version Control

Track template and function usage:

// Document template usage
// Generated with claude-setup v2.1.0
// Template: fullstack-typescript
// Date: 2024-01-01

Available Functions Library

Core Functions

  • createProject() - Project initialization
  • generateCRUD() - CRUD operations
  • setupAuth() - Authentication systems
  • createAPI() - REST/GraphQL APIs
  • setupDatabase() - Database configuration

Testing Functions

  • createTestSuite() - Test generation
  • setupTestData() - Mock data creation
  • createFixtures() - Test fixtures
  • setupTestDB() - Test database

Deployment Functions

  • createDockerfile() - Container setup
  • setupCI() - CI/CD pipelines
  • createK8sConfig() - Kubernetes deployment
  • setupMonitoring() - Observability

Utility Functions

  • formatCode() - Code formatting
  • validateProject() - Project validation
  • optimizeBundle() - Build optimization
  • generateDocs() - Documentation generation

Next Steps