[ PROMPT_NODE_23972 ]
API 设计模式
[ SKILL_DOCUMENTATION ]
# 常见模式
## 使用自动分页列出所有资源
**问题:** API 返回分页结果。默认页面大小为 20。
**解决方案:** 使用 SDK 自动分页功能遍历所有结果。
typescript
// TypeScript
for await (const zone of client.zones.list()) {
console.log(zone.name);
}
python
# Python
for zone in client.zones.list():
print(zone.name)
go
// Go
iter := client.Zones.ListAutoPaging(ctx, cloudflare.ZoneListParams{})
for iter.Next() {
fmt.Println(iter.Current().Name)
}
## 带重试的错误处理
**问题:** 速率限制 (429) 和瞬时错误需要重试。
**解决方案:** SDK 会自动进行指数退避重试。可根据需要自定义。
typescript
// 为高频速率限制的操作增加重试次数
const client = new Cloudflare({ maxRetries: 5 });
try {
const zone = await client.zones.create({ /* ... */ });
} catch (err) {
if (err instanceof Cloudflare.RateLimitError) {
// 已自动重试 5 次并退避
const retryAfter = err.headers['retry-after'];
console.log(`速率受限。请在 ${retryAfter}s 后重试`);
}
}
## 批量并行操作
**问题:** 需要快速创建多个资源。
**解决方案:** 使用 `Promise.all()` 进行并行请求(注意速率限制)。
typescript
// 并行创建多个 DNS 记录
const records = ['www', 'api', 'cdn'].map(subdomain =>
client.dns.records.create({
zone_id: 'zone-id',
type: 'A',
name: `${subdomain}.example.com`,
content: '192.0.2.1',
})
);
await Promise.all(records);
**控制并发**(避免速率限制):
typescript
import pLimit from 'p-limit';
const limit = pLimit(10); // 最大 10 个并发
const subdomains = ['www', 'api', 'cdn', /* 更多 */];
const records = subdomains.map(subdomain =>
limit(() => client.dns.records.create({
zone_id: 'zone-id',
type: 'A',
name: `${subdomain}.example.com`,
content: '192.0.2.1',
}))
);
await Promise.all(records);
## 区域 CRUD 工作流
typescript
// 创建
const zone = await client.zones.create({
account: { id: 'account-id' },
name: 'example.com',
type: 'full',
});
// 读取
const fetched = await client.zones.get({ zone_id: zone.id });
// 更新
await client.zones.edit(zone.id, { paused: false });
// 删除
await client.zones.delete(zone.id);
## DNS 批量更新
typescript
// 获取所有 A 记录
const records = [];
for await (const record of client.dns.records.list({
zone_id: 'zone-id',
type: 'A