Advanced Recipes
Production-proven multi-step prompts for API migrations, DB schema changes, large refactors, and infrastructure.
Read time: 18 min
title: "Advanced Recipes" description: "Production-proven multi-step prompts for API migrations, DB schema changes, large refactors, and infrastructure." section: "Full Guide" readTime: "18 min"
Advanced Recipes
Copy-paste prompt templates for complex real-world tasks.
REST → GraphQL Migration
Use Parallel Agents approach: REST API stays live on port 3000 while GraphQL runs on 3001.
Phase 1 — Analysis:
@instructions.md @src/routes/
Analyze this REST API and plan a GraphQL migration:
1. List all REST endpoints with methods, params, auth requirements
2. Identify shared data structures and relationships
3. Map REST to GraphQL: queries/mutations/subscriptions
4. Flag N+1 query risks (mark with [DATALOADER NEEDED])
5. Estimate migration effort per group
Wait for approval before Phase 2.
Phase 2 — GraphQL server setup:
Set up Apollo Server 4 with:
- Type generation (graphql-code-generator)
- DataLoader for all N+1 relationships flagged in Phase 1
- JWT auth middleware (port over from existing Express auth)
- Error handling matching our AppError class
- Run on port 3001
Write integration tests. Run them. Wait for approval.
Phase 3 — Route-by-route migration (repeat per endpoint group):
Migrate User endpoints:
- REST: GET /users/:id → GraphQL: query { user(id) }
- REST: POST /users → GraphQL: mutation { createUser }
- REST: PUT /users/:id → GraphQL: mutation { updateUser }
Keep REST on port 3000. New GraphQL on port 3001.
Test both respond identically. Wait.
Phase 4 — Cutover:
Switch API gateway to GraphQL after load test passes.
Keep REST as fallback for 2 weeks.
Remove REST routes [date].
Database Schema Migration (Prisma)
Adding soft deletes without breaking existing queries.
@instructions.md @prisma/schema.prisma @src/repositories/
Add soft delete to User and Post models (no hard deletes ever).
Schema changes:
1. Add to User: deletedAt DateTime? (null = active)
2. Add to Post: deletedAt DateTime? (null = active)
3. Do NOT use Prisma middleware — query-level filtering only
SoftDeleteRepository base class:
- findActive(): WHERE deletedAt IS NULL
- softDelete(id): SET deletedAt = NOW()
- findAll(): no filter (admin use)
Migration:
1. Create Prisma migration file
2. Zero-downtime: add column nullable with default null
3. Data: verify no unintended deletions
4. Indexes: add to deletedAt column
Tests:
- Regular query: deleted records excluded
- softDelete(): sets timestamp
- Admin query: shows all
- Cascade: deleting User soft-deletes Posts
Run: npx prisma migrate dev
Run tests. Wait for approval.
Large-Scale Refactor: Class Components → Hooks
Batch + template strategy. Never do all files at once.
Phase 1 — Audit:
@src/components/
Audit React class component usage:
1. Count: total class components
2. Categorize: lifecycle methods used per component
3. Risk: flag complex state management, rare lifecycle methods
4. Estimate lines of code per component
5. Prioritize migration order: simplest first
Output: table sorted by complexity ASC
Phase 2 — Create template:
Convert UserCard.tsx to functional component as our reference template:
- componentDidMount → useEffect with []
- componentDidUpdate → useEffect with dependencies
- componentWillUnmount → useEffect cleanup
- PureComponent → React.memo
Run existing tests. If none: write before converting.
Output the template we'll follow for all others.
Phase 3 — Batch migration (5 components at a time):
Convert the next 5 components in our priority list using the UserCard template.
After each: verify tests pass and runtime behavior unchanged.
Commit after each successful conversion.
Major Dependency Upgrade (React 17 → 18)
@instructions.md @package.json @src/
React 17 → 18 migration:
Phase 1: Audit
- List all ReactDOM.render() calls → need to migrate to createRoot
- Find deprecated lifecycle methods (UNSAFE_*)
- List all dependencies needing React 18–compatible versions
- Identify Concurrent Mode incompatibilities
Phase 2: Prepare
- Create compatibility branch
- Update peer deps order (React first, then ecosystem)
- Create migration notes doc
Phase 3: Execute
- Update React and ReactDOM
- Replace ReactDOM.render() with createRoot()
- Fix breaking changes (Automatic JSX Transform, strict effect behavior)
- DO NOT enable StrictMode until all fixes verified
Phase 4: Verify
- npm test passes
- No hydration errors
- Confirm useEffect fires once in development
Micro-Frontend Integration
Integrating a new React app into a monolith via Module Federation.
@instructions.md @src/ @webpack.config.js
Integrate checkout micro-frontend via Webpack 5 Module Federation.
Checkout app exposes: CheckoutWidget, useCheckout, CartContext
Main app consumes it.
Implementation:
1. Main app webpack.config: add ModuleFederationPlugin as remote
url: http://localhost:3001/remoteEntry.js
2. Create type declarations for remote:
declare module "checkout/CheckoutWidget" {
const CheckoutWidget: React.FC<{onComplete: () => void}>;
export default CheckoutWidget;
}
3. Lazy import in main app:
const CheckoutWidget = React.lazy(() => import("checkout/CheckoutWidget"))
4. Error boundary with fallback:
If checkout fails, show fallback "Checkout unavailable" message
5. Tests: mock the remote, verify lazy load + error boundary
Run tests. Wait.
Infrastructure as Code (Terraform + Context7)
@instructions.md
Use Context7 for Terraform AWS docs (exact module versions, not training data).
Create infrastructure for production Next.js app:
Components:
- ECS Fargate cluster (auto-scaling 2–10 instances, CPU/memory triggers)
- ALB (HTTPS only, HTTP redirects)
- Aurora Serverless v2 (PostgreSQL), multi-AZ
- ElastiCache Redis (replication group)
- S3 + CloudFront (static assets)
- Route53 + ACM certificate
Security:
- VPC with private subnets for ECS/RDS/Redis
- Public subnets for ALB only
- Security groups with least-privilege
- Secrets Manager for DB credentials; NO hardcoded secrets
Files:
- main.tf — providers, backend config
- networking.tf — VPC, subnets
- compute.tf — ECS, ALB
- data.tf — Aurora, Redis
- cdn.tf — S3, CloudFront
- variables.tf + outputs.tf
Validate: terraform validate && terraform plan -out=tfplan
Serverless / Lambda
@instructions.md
Create serverless API with Lambda, API Gateway, DynamoDB:
Architecture:
- 4 Lambdas: createUser, getUser, updateUser, deleteUser
- Single-table DynamoDB design (PK: USER#userId, SK: PROFILE#v1)
- API Gateway v2 (HTTP API) — faster and cheaper than REST API
Lambda standards:
- Runtime: Node.js 20
- ESM modules (import/export, not require)
- Use AWS SDK v3 (DynamoDB.DocumentClient)
- PowerTools Lambda: Logger, Tracer, Metrics
- Under 50ms cold start requirement
DynamoDB:
- Single-table design
- GSI on email attribute
- TTL on session tokens
Infrastructure: SAM template
Tests: unit tests mocking DynamoDB, test each Lambda independently
Deploy: sam deploy --guided