instantly-sdk-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Instantly SDK Patterns

Instantly SDK 模式

Overview

概述

Production-ready patterns for Instantly SDK usage in TypeScript and Python.
适用于TypeScript和Python的Instantly SDK生产就绪型使用模式。

Prerequisites

前置要求

  • Completed
    instantly-install-auth
    setup
  • 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

错误处理

PatternUse CaseBenefit
Safe wrapperAll API callsPrevents uncaught exceptions
Retry logicTransient failuresImproves reliability
Type guardsResponse validationCatches API changes
LoggingAll operationsDebugging 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
instantly-core-workflow-a
for real-world usage.
instantly-core-workflow-a
中应用这些模式,进行实际场景使用。