instantly-sdk-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseInstantly SDK Patterns
Instantly SDK 模式
Overview
概述
Production-ready patterns for Instantly SDK usage in TypeScript and Python.
适用于TypeScript和Python的Instantly SDK生产就绪型使用模式。
Prerequisites
前置要求
- Completed setup
instantly-install-auth - Familiarity with async/await patterns
- Understanding of error handling best practices
- 已完成设置
instantly-install-auth - 熟悉async/await模式
- 了解错误处理最佳实践
Instructions
操作步骤
Step 1: Implement Singleton Pattern (Recommended)
步骤1:实现单例模式(推荐)
typescript
// src/instantly/client.ts
import { InstantlyClient } from '@instantly/sdk';
let instance: InstantlyClient | null = null;
export function getInstantlyClient(): InstantlyClient {
if (!instance) {
instance = new InstantlyClient({
apiKey: process.env.INSTANTLY_API_KEY!,
// Additional options
});
}
return instance;
}typescript
// src/instantly/client.ts
import { InstantlyClient } from '@instantly/sdk';
let instance: InstantlyClient | null = null;
export function getInstantlyClient(): InstantlyClient {
if (!instance) {
instance = new InstantlyClient({
apiKey: process.env.INSTANTLY_API_KEY!,
// Additional options
});
}
return instance;
}Step 2: Add Error Handling Wrapper
步骤2:添加错误处理包装器
typescript
import { InstantlyError } from '@instantly/sdk';
async function safeInstantlyCall<T>(
operation: () => Promise<T>
): Promise<{ data: T | null; error: Error | null }> {
try {
const data = await operation();
return { data, error: null };
} catch (err) {
if (err instanceof InstantlyError) {
console.error({
code: err.code,
message: err.message,
});
}
return { data: null, error: err as Error };
}
}typescript
import { InstantlyError } from '@instantly/sdk';
async function safeInstantlyCall<T>(
operation: () => Promise<T>
): Promise<{ data: T | null; error: Error | null }> {
try {
const data = await operation();
return { data, error: null };
} catch (err) {
if (err instanceof InstantlyError) {
console.error({
code: err.code,
message: err.message,
});
}
return { data: null, error: err as Error };
}
}Step 3: Implement Retry Logic
步骤3:实现重试逻辑
typescript
async function withRetry<T>(
operation: () => Promise<T>,
maxRetries = 3,
backoffMs = 1000
): Promise<T> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (err) {
if (attempt === maxRetries) throw err;
const delay = backoffMs * Math.pow(2, attempt - 1);
await new Promise(r => setTimeout(r, delay));
}
}
throw new Error('Unreachable');
}typescript
async function withRetry<T>(
operation: () => Promise<T>,
maxRetries = 3,
backoffMs = 1000
): Promise<T> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (err) {
if (attempt === maxRetries) throw err;
const delay = backoffMs * Math.pow(2, attempt - 1);
await new Promise(r => setTimeout(r, delay));
}
}
throw new Error('Unreachable');
}Output
输出结果
- Type-safe client singleton
- Robust error handling with structured logging
- Automatic retry with exponential backoff
- Runtime validation for API responses
- 类型安全的客户端单例
- 带结构化日志的健壮错误处理
- 带指数退避的自动重试
- API响应的运行时验证
Error Handling
错误处理
| Pattern | Use Case | Benefit |
|---|---|---|
| Safe wrapper | All API calls | Prevents uncaught exceptions |
| Retry logic | Transient failures | Improves reliability |
| Type guards | Response validation | Catches API changes |
| Logging | All operations | Debugging and monitoring |
| 模式 | 适用场景 | 优势 |
|---|---|---|
| 安全包装器 | 所有API调用 | 防止未捕获异常 |
| 重试逻辑 | 临时故障 | 提升可靠性 |
| 类型守卫 | 响应验证 | 捕获API变更 |
| 日志记录 | 所有操作 | 调试与监控 |
Examples
示例
Factory Pattern (Multi-tenant)
工厂模式(多租户)
typescript
const clients = new Map<string, InstantlyClient>();
export function getClientForTenant(tenantId: string): InstantlyClient {
if (!clients.has(tenantId)) {
const apiKey = getTenantApiKey(tenantId);
clients.set(tenantId, new InstantlyClient({ apiKey }));
}
return clients.get(tenantId)!;
}typescript
const clients = new Map<string, InstantlyClient>();
export function getClientForTenant(tenantId: string): InstantlyClient {
if (!clients.has(tenantId)) {
const apiKey = getTenantApiKey(tenantId);
clients.set(tenantId, new InstantlyClient({ apiKey }));
}
return clients.get(tenantId)!;
}Python Context Manager
Python 上下文管理器
python
from contextlib import asynccontextmanager
from instantly import InstantlyClient
@asynccontextmanager
async def get_instantly_client():
client = InstantlyClient()
try:
yield client
finally:
await client.close()python
from contextlib import asynccontextmanager
from instantly import InstantlyClient
@asynccontextmanager
async def get_instantly_client():
client = InstantlyClient()
try:
yield client
finally:
await client.close()Zod Validation
Zod 验证
typescript
import { z } from 'zod';
const instantlyResponseSchema = z.object({
id: z.string(),
status: z.enum(['active', 'inactive']),
createdAt: z.string().datetime(),
});typescript
import { z } from 'zod';
const instantlyResponseSchema = z.object({
id: z.string(),
status: z.enum(['active', 'inactive']),
createdAt: z.string().datetime(),
});Resources
参考资源
Next Steps
后续步骤
Apply patterns in for real-world usage.
instantly-core-workflow-a在中应用这些模式,进行实际场景使用。
instantly-core-workflow-a