Skill站外收录 @skilllib/skill-2014279417088913411
customerio-sdk-patterns
提供类型安全的用户识别与事件追踪能力,支持自动重试、批量处理及资源复用,适用于高可靠性的消息推送场景,通过队列缓冲和指数退避降低系统负载。
商业与营销 AI 技能
Skills.MD
# Customer.io SDK Patterns
## Overview
Production-ready patterns for Customer.io SDK usage including error handling, batching, and type safety.
## Prerequisites
- Customer.io SDK installed
- TypeScript project (recommended)
- Understanding of async/await patterns
## Instructions
### Pattern 1: Type-Safe Client
```typescript
// types/customerio.ts
export interface UserAttributes {
email: string;
first_name?: string;
last_name?: string;
created_at?: number;
plan?: 'free' | 'pro' | 'enterprise';
[key: string]: string | number | boolean | undefined;
}
export interface EventData {
[key: string]: string | number | boolean | object;
}
export type EventName =
| 'signed_up'
| 'subscription_started'
| 'subscription_cancelled'
| 'feature_used'
| 'email_verified';
// lib/customerio-client.ts
import { TrackClient, RegionUS } from '@customerio/track';
import type { UserAttributes, EventData, EventName } from '../types/customerio';
export class TypedCustomerIO {
private client: TrackClient;
constructor() {
this.client = new TrackClient(
process.env.CUSTOMERIO_SITE_ID!,
process.env.CUSTOMERIO_API_KEY!,
{ region: RegionUS }
);
}
async identify(userId: string, attributes: UserAttributes): Promise<void> {
await this.client.identify(userId, {
...attributes,
_updated_at: Math.floor(Date.now() / 1000)
});
}
async track(userId: string, event: EventName, data?: EventData): Promise<void> {
await this.client.track(userId, { name: event, data });
}
}
```
### Pattern 2: Retry with Exponential Backoff
```typescript
// lib/customerio-resilient.ts
import { TrackClient } from '@customerio/track';
interface RetryConfig {
maxRetries: number;
baseDelay: number;
maxDelay: number;
}
const defaultRetryConfig: RetryConfig = {
maxRetries: 3,
baseDelay: 1000,
maxDelay: 10000
};
async function withRetry<T>(
operation: () => Promise<T>,
config: RetryConfig = defaultRetryConfig
): Promise<T> {
let lastError: Error | undefined;
for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error as Error;
if (attempt === config.maxRetries) break;
// Don't retry on 4xx errors (client errors)
if (error instanceof Error && error.message.includes('4')) {
throw error;
}
const delay = Math.min(
config.baseDelay * Math.pow(2, attempt),
config.maxDelay
);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw lastError;
}
export class ResilientCustomerIO {
private client: TrackClient;
constructor(siteId: string, apiKey: string) {
this.client = new TrackClient(siteId, apiKey, { region: RegionUS });
}
async identify(userId: string, attributes: Record<string, any>) {
return withRetry(() => this.client.identify(userId, attributes));
}
async track(userId: string, event: string, data?: Record<string, any>) {
return withRetry(() => this.client.track(userId, { name: event, data }));
}
}
```
### Pattern 3: Event Queue with Batching
```typescript
// lib/customerio-queue.ts
interface QueuedEvent {
userId: string;
event: string;
data?: Record<string, any>;
timestamp: number;
}
export class CustomerIOQueue {
private queue: QueuedEvent[] = [];
private flushInterval: NodeJS.Timer | null = null;
private maxBatchSize = 100;
private flushIntervalMs = 5000;
constructor(private client: TrackClient) {
this.startAutoFlush();
}
enqueue(userId: string, event: string, data?: Record<string, any>) {
this.queue.push({
userId,
event,
data,
timestamp: Date.now()
});
if (this.queue.length >= this.maxBatchSize) {
this.flush();
}
}
async flush(): Promise<void> {
if (this.queue.length === 0) return;
const batch = this.queue.splice(0, this.maxBatchSize);
await Promise.allSettled(
batch.map(item =>
this.client.track(item.userId, {
name: item.event,
data: { ...item.data, _queued_at: item.timestamp }
})
)
);
}
private startAutoFlush() {
this.flushInterval = setInterval(() => this.flush(), this.flushIntervalMs);
}
async shutdown(): Promise<void> {
if (this.flushInterval) {
clearInterval(this.flushInterval);
}
await this.flush();
}
}
```
### Pattern 4: Singleton with Lazy Initialization
```typescript
// lib/customerio-singleton.ts
import { TrackClient, RegionUS } from '@customerio/track';
let instance: TrackClient | null = null;
export function getCustomerIO(): TrackClient {
if (!instance) {
if (!process.env.CUSTOMERIO_SITE_ID || !process.env.CUSTOMERIO_API_KEY) {
throw new Error('Customer.io credentials not configured');
}
instance = new TrackClient(
process.env.CUSTOMERIO_SITE_ID,
process.env.CUSTOMERIO_API_KEY,
{ region: RegionUS }
);
}
return instance;
}
// Usage
import { getCustomerIO } from './lib/customerio-singleton';
await getCustomerIO().identify('user-123', { email: 'user@example.com' });
```
## Output
- Type-safe Customer.io client
- Resilient error handling with retries
- Event batching for high-volume scenarios
- Singleton pattern for resource efficiency
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| Type mismatch | Invalid attribute type | Use TypeScript interfaces |
| Queue overflow | Too many events | Increase flush frequency or batch size |
| Retry exhausted | Persistent failure | Check network and credentials |
## Resources
- [Customer.io SDK GitHub](https://github.com/customerio/customerio-node)
- [API Rate Limits](https://customer.io/docs/api/track/#section/Limits)
## Next Steps
After implementing patterns, proceed to `customerio-primary-workflow` to implement messaging workflows.
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「customerio-sdk-patterns」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次