Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/api/patterns.md
1# Common Patterns23## List All with Auto-Pagination45**Problem:** API returns paginated results. Default page size is 20.67**Solution:** Use SDK auto-pagination to iterate all results.89```typescript10// TypeScript11for await (const zone of client.zones.list()) {12console.log(zone.name);13}14```1516```python17# Python18for zone in client.zones.list():19print(zone.name)20```2122```go23// Go24iter := client.Zones.ListAutoPaging(ctx, cloudflare.ZoneListParams{})25for iter.Next() {26fmt.Println(iter.Current().Name)27}28```2930## Error Handling with Retry3132**Problem:** Rate limits (429) and transient errors need retry.3334**Solution:** SDKs auto-retry with exponential backoff. Customize as needed.3536```typescript37// Increase retries for rate-limit-heavy operations38const client = new Cloudflare({ maxRetries: 5 });3940try {41const zone = await client.zones.create({ /* ... */ });42} catch (err) {43if (err instanceof Cloudflare.RateLimitError) {44// Already retried 5 times with backoff45const retryAfter = err.headers['retry-after'];46console.log(`Rate limited. Retry after ${retryAfter}s`);47}48}49```5051## Batch Parallel Operations5253**Problem:** Need to create multiple resources quickly.5455**Solution:** Use `Promise.all()` for parallel requests (respect rate limits).5657```typescript58// Create multiple DNS records in parallel59const records = ['www', 'api', 'cdn'].map(subdomain =>60client.dns.records.create({61zone_id: 'zone-id',62type: 'A',63name: `${subdomain}.example.com`,64content: '192.0.2.1',65})66);67await Promise.all(records);68```6970**Controlled concurrency** (avoid rate limits):7172```typescript73import pLimit from 'p-limit';74const limit = pLimit(10); // Max 10 concurrent7576const subdomains = ['www', 'api', 'cdn', /* many more */];77const records = subdomains.map(subdomain =>78limit(() => client.dns.records.create({79zone_id: 'zone-id',80type: 'A',81name: `${subdomain}.example.com`,82content: '192.0.2.1',83}))84);85await Promise.all(records);86```8788## Zone CRUD Workflow8990```typescript91// Create92const zone = await client.zones.create({93account: { id: 'account-id' },94name: 'example.com',95type: 'full',96});9798// Read99const fetched = await client.zones.get({ zone_id: zone.id });100101// Update102await client.zones.edit(zone.id, { paused: false });103104// Delete105await client.zones.delete(zone.id);106```107108## DNS Bulk Update109110```typescript111// Fetch all A records112const records = [];113for await (const record of client.dns.records.list({114zone_id: 'zone-id',115type: 'A',116})) {117records.push(record);118}119120// Update all to new IP121await Promise.all(records.map(record =>122client.dns.records.update({123zone_id: 'zone-id',124dns_record_id: record.id,125type: 'A',126name: record.name,127content: '203.0.113.1', // New IP128proxied: record.proxied,129ttl: record.ttl,130})131));132```133134## Filter and Collect Results135136```typescript137// Find all proxied A records138const proxiedRecords = [];139for await (const record of client.dns.records.list({140zone_id: 'zone-id',141type: 'A',142})) {143if (record.proxied) {144proxiedRecords.push(record);145}146}147```148149## Error Recovery Pattern150151```typescript152async function createZoneWithRetry(name: string, maxAttempts = 3) {153for (let attempt = 1; attempt <= maxAttempts; attempt++) {154try {155return await client.zones.create({156account: { id: 'account-id' },157name,158type: 'full',159});160} catch (err) {161if (err instanceof Cloudflare.RateLimitError && attempt < maxAttempts) {162const retryAfter = parseInt(err.headers['retry-after'] || '5');163console.log(`Rate limited, waiting ${retryAfter}s (retry ${attempt}/${maxAttempts})`);164await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));165} else {166throw err;167}168}169}170}171```172173## Conditional Update Pattern174175```typescript176// Only update if zone is active177const zone = await client.zones.get({ zone_id: 'zone-id' });178if (zone.status === 'active') {179await client.zones.edit(zone.id, { paused: false });180}181```182183## Batch with Error Handling184185```typescript186// Process multiple zones, continue on errors187const results = await Promise.allSettled(188zoneIds.map(id => client.zones.get({ zone_id: id }))189);190191results.forEach((result, i) => {192if (result.status === 'fulfilled') {193console.log(`Zone ${i}: ${result.value.name}`);194} else {195console.error(`Zone ${i} failed:`, result.reason.message);196}197});198```199200## See Also201202- [api.md](./api.md) - SDK client initialization, basic operations203- [gotchas.md](./gotchas.md) - Rate limits, common errors204- [configuration.md](./configuration.md) - SDK configuration options205