application-patterns
Common application development patterns and implementations
What this skill does
# Application Development Patterns
## Overview
Common patterns for building real-world applications. These patterns solve recurring problems in application development.
---
## CRUD Applications
### Data Flow Pattern
```
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
│ Form │ ──→ │Validate │ ──→ │ Service │ ──→ │ DB │
└─────────┘ └─────────┘ └─────────┘ └─────────┘
↑ │
└───────────── Response ←───────────────────────┘
```
### Form Handling Best Practices
```typescript
// 1. Validation schema (shared frontend/backend)
const userSchema = z.object({
email: z.string().email(),
name: z.string().min(2).max(100),
role: z.enum(['admin', 'user', 'guest'])
});
// 2. Server action with error handling
async function createUser(formData: FormData) {
const result = userSchema.safeParse(Object.fromEntries(formData));
if (!result.success) {
return { error: result.error.flatten() };
}
try {
const user = await db.user.create({ data: result.data });
return { success: true, data: user };
} catch (e) {
if (e.code === 'P2002') {
return { error: { email: 'Email already exists' } };
}
throw e;
}
}
```
---
## User Authentication
### Authentication Flow
```
┌────────────────────────────────────────────────────────────┐
│ Authentication Flows │
├────────────────────────────────────────────────────────────┤
│ │
│ Email/Password: │
│ Login → Validate → Create Session → Set Cookie → Redirect │
│ │
│ OAuth (Social Login): │
│ Redirect → Provider Auth → Callback → Upsert User → Done │
│ │
│ Magic Link: │
│ Email → Generate Token → Send Link → Verify → Login │
│ │
└────────────────────────────────────────────────────────────┘
```
### Session Management
| Strategy | Pros | Cons |
|----------|------|------|
| JWT | Stateless, scalable | Can't revoke easily |
| Server Session | Revocable, secure | Requires session store |
| Hybrid | Best of both | More complex |
### Security Checklist
- [ ] Password hashing (bcrypt/argon2)
- [ ] Rate limiting on login
- [ ] CSRF protection
- [ ] Secure cookie settings (httpOnly, secure, sameSite)
- [ ] Account lockout after failed attempts
- [ ] Password reset token expiration
---
## Admin Dashboards
### Data Table Pattern
```typescript
// Reusable data table with sorting, filtering, pagination
interface DataTableProps<T> {
data: T[];
columns: ColumnDef<T>[];
pagination: { page: number; pageSize: number; total: number };
sorting: { field: string; direction: 'asc' | 'desc' }[];
filters: Record<string, unknown>;
onStateChange: (state: TableState) => void;
}
// Server-side handling
async function getUsers(params: TableState) {
const { page, pageSize, sorting, filters } = params;
const query = {
where: buildWhereClause(filters),
orderBy: buildOrderBy(sorting),
skip: (page - 1) * pageSize,
take: pageSize,
};
const [users, total] = await Promise.all([
db.user.findMany(query),
db.user.count({ where: query.where })
]);
return { data: users, total };
}
```
### Bulk Operations
```typescript
// Safe bulk delete with confirmation
async function bulkDelete(ids: string[]) {
// 1. Validate permissions for each item
const items = await db.item.findMany({
where: { id: { in: ids } },
select: { id: true, ownerId: true }
});
const authorized = items.filter(item =>
canDelete(currentUser, item)
);
// 2. Soft delete or hard delete
await db.item.updateMany({
where: { id: { in: authorized.map(i => i.id) } },
data: { deletedAt: new Date() }
});
return {
deleted: authorized.length,
skipped: ids.length - authorized.length
};
}
```
---
## File Management
### Upload Strategies
| Method | Use Case | Max Size |
|--------|----------|----------|
| Direct to server | Small files | ~10MB |
| Presigned URL | Large files | Unlimited |
| Chunked upload | Very large files | Unlimited |
| Resumable | Unreliable network | Unlimited |
### Presigned URL Flow
```
Client Server S3
│ │ │
│── Request upload URL ──→│ │
│ │── Generate presigned ─→│
│←── Return presigned URL─│ │
│ │ │
│───────── Upload file directly ─────────────────→│
│ │ │
│── Confirm upload ──────→│ │
│ │── Verify file exists ─→│
│←── Success ─────────────│ │
```
### Image Processing Pipeline
```typescript
async function processUpload(file: File) {
// 1. Validate file type and size
if (!ALLOWED_TYPES.includes(file.type)) {
throw new Error('Invalid file type');
}
// 2. Generate variants
const variants = await Promise.all([
sharp(file.buffer).resize(100, 100).toBuffer(), // thumbnail
sharp(file.buffer).resize(800, 600).toBuffer(), // medium
sharp(file.buffer).resize(1920, 1080).toBuffer(), // large
]);
// 3. Upload to CDN
const urls = await uploadToS3(variants);
// 4. Store metadata
return db.image.create({
data: {
original: urls.original,
thumbnail: urls.thumbnail,
medium: urls.medium,
large: urls.large,
mimeType: file.type,
size: file.size,
}
});
}
```
---
## Search Implementation
### Search Architecture
```
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Database │ ──→ │ Sync │ ──→ │ Search │
│ (Primary) │ │ Worker │ │ Engine │
└──────────────┘ └──────────────┘ └──────────────┘
↑
│
┌──────────────┐ ┌──────────────┐ │
│ Client │ ──→ │ Search API │ ────────────┘
└──────────────┘ └──────────────┘
```
### Search Features Checklist
- [ ] Full-text search
- [ ] Faceted filtering
- [ ] Autocomplete/suggestions
- [ ] Typo tolerance (fuzzy matching)
- [ ] Highlighting
- [ ] Synonyms
- [ ] Relevance tuning
---
## Workflow Engines
### State Machine Pattern
```typescript
const orderStateMachine = {
initial: 'pending',
states: {
pending: {
on: {
PAY: 'paid',
CANCEL: 'cancelled'
}
},
paid: {
on: {
SHIP: 'shipped',
REFUND: 'refunded'
}
},
shipped: {
on: {
DELIVER: 'delivered',
RETURN: 'returned'
}
},
delivered: { type: 'final' },
cancelled: { type: 'final' },
refunded: { type: 'final' },
returned: {
on: {
REFUND: 'refunded'
}
}
}
};
```
### Approval Workflow
```typescript
interface ApprovalStep {
id: string;
approvers: string[]; // User IDs or roles
requiredApprovals: number; // How many need to approve
timeout?: Duration; // Auto-escalate after
escalateTo?: string; // Next approver on timeout
}
async function processApproval(stepId: string, userId: string, decision: 'approve' | 'reject') {
const step = await db.approvalStep.findUnique({ where: { id: stepId } });
// Record decision
await db.approval.create({
data: { stepId, userId, decision, timestamp: new Date() }
});
// Check if complete
const approvals = await db.approval.count({
where: { stepId, decision: 'approve' }
});
if (approvals >= step.requiredApprovals) {
await advanceToNextStep(stRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.