posthog-reference-architecture
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePostHog Reference Architecture
PostHog参考架构
Overview
概述
Production-ready architecture patterns for PostHog integrations.
适用于PostHog集成的生产就绪型架构模式。
Prerequisites
前置条件
- Understanding of layered architecture
- PostHog SDK knowledge
- TypeScript project setup
- Testing framework configured
- 了解分层架构
- 掌握PostHog SDK知识
- 已完成TypeScript项目搭建
- 已配置测试框架
Project Structure
项目结构
my-posthog-project/
├── src/
│ ├── posthog/
│ │ ├── client.ts # Singleton client wrapper
│ │ ├── config.ts # Environment configuration
│ │ ├── types.ts # TypeScript types
│ │ ├── errors.ts # Custom error classes
│ │ └── handlers/
│ │ ├── webhooks.ts # Webhook handlers
│ │ └── events.ts # Event processing
│ ├── services/
│ │ └── posthog/
│ │ ├── index.ts # Service facade
│ │ ├── sync.ts # Data synchronization
│ │ └── cache.ts # Caching layer
│ ├── api/
│ │ └── posthog/
│ │ └── webhook.ts # Webhook endpoint
│ └── jobs/
│ └── posthog/
│ └── sync.ts # Background sync job
├── tests/
│ ├── unit/
│ │ └── posthog/
│ └── integration/
│ └── posthog/
├── config/
│ ├── posthog.development.json
│ ├── posthog.staging.json
│ └── posthog.production.json
└── docs/
└── posthog/
├── SETUP.md
└── RUNBOOK.mdmy-posthog-project/
├── src/
│ ├── posthog/
│ │ ├── client.ts # 单例客户端封装
│ │ ├── config.ts # 环境配置
│ │ ├── types.ts # TypeScript类型定义
│ │ ├── errors.ts # 自定义错误类
│ │ └── handlers/
│ │ ├── webhooks.ts # Webhook处理器
│ │ └── events.ts # 事件处理
│ ├── services/
│ │ └── posthog/
│ │ ├── index.ts # 服务外观
│ │ ├── sync.ts # 数据同步
│ │ └── cache.ts # 缓存层
│ ├── api/
│ │ └── posthog/
│ │ └── webhook.ts # Webhook端点
│ └── jobs/
│ └── posthog/
│ └── sync.ts # 后台同步任务
├── tests/
│ ├── unit/
│ │ └── posthog/
│ └── integration/
│ └── posthog/
├── config/
│ ├── posthog.development.json
│ ├── posthog.staging.json
│ └── posthog.production.json
└── docs/
└── posthog/
├── SETUP.md
└── RUNBOOK.mdLayer Architecture
分层架构
┌─────────────────────────────────────────┐
│ API Layer │
│ (Controllers, Routes, Webhooks) │
├─────────────────────────────────────────┤
│ Service Layer │
│ (Business Logic, Orchestration) │
├─────────────────────────────────────────┤
│ PostHog Layer │
│ (Client, Types, Error Handling) │
├─────────────────────────────────────────┤
│ Infrastructure Layer │
│ (Cache, Queue, Monitoring) │
└─────────────────────────────────────────┘┌─────────────────────────────────────────┐
│ API层 │
│ (控制器、路由、Webhook) │
├─────────────────────────────────────────┤
│ 服务层 │
│ (业务逻辑、编排管理) │
├─────────────────────────────────────────┤
│ PostHog层 │
│ (客户端、类型定义、错误处理) │
├─────────────────────────────────────────┤
│ 基础设施层 │
│ (缓存、队列、监控) │
└─────────────────────────────────────────┘Key Components
核心组件
Step 1: Client Wrapper
步骤1:客户端封装
typescript
// src/posthog/client.ts
export class PostHogService {
private client: PostHogClient;
private cache: Cache;
private monitor: Monitor;
constructor(config: PostHogConfig) {
this.client = new PostHogClient(config);
this.cache = new Cache(config.cacheOptions);
this.monitor = new Monitor('posthog');
}
async get(id: string): Promise<Resource> {
return this.cache.getOrFetch(id, () =>
this.monitor.track('get', () => this.client.get(id))
);
}
}typescript
// src/posthog/client.ts
export class PostHogService {
private client: PostHogClient;
private cache: Cache;
private monitor: Monitor;
constructor(config: PostHogConfig) {
this.client = new PostHogClient(config);
this.cache = new Cache(config.cacheOptions);
this.monitor = new Monitor('posthog');
}
async get(id: string): Promise<Resource> {
return this.cache.getOrFetch(id, () =>
this.monitor.track('get', () => this.client.get(id))
);
}
}Step 2: Error Boundary
步骤2:错误边界
typescript
// src/posthog/errors.ts
export class PostHogServiceError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly retryable: boolean,
public readonly originalError?: Error
) {
super(message);
this.name = 'PostHogServiceError';
}
}
export function wrapPostHogError(error: unknown): PostHogServiceError {
// Transform SDK errors to application errors
}typescript
// src/posthog/errors.ts
export class PostHogServiceError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly retryable: boolean,
public readonly originalError?: Error
) {
super(message);
this.name = 'PostHogServiceError';
}
}
export function wrapPostHogError(error: unknown): PostHogServiceError {
// 将SDK错误转换为应用级错误
}Step 3: Health Check
步骤3:健康检查
typescript
// src/posthog/health.ts
export async function checkPostHogHealth(): Promise<HealthStatus> {
try {
const start = Date.now();
await posthogClient.ping();
return {
status: 'healthy',
latencyMs: Date.now() - start,
};
} catch (error) {
return { status: 'unhealthy', error: error.message };
}
}typescript
// src/posthog/health.ts
export async function checkPostHogHealth(): Promise<HealthStatus> {
try {
const start = Date.now();
await posthogClient.ping();
return {
status: 'healthy',
latencyMs: Date.now() - start,
};
} catch (error) {
return { status: 'unhealthy', error: error.message };
}
}Data Flow Diagram
数据流图
User Request
│
▼
┌─────────────┐
│ API │
│ Gateway │
└──────┬──────┘
│
▼
┌─────────────┐ ┌─────────────┐
│ Service │───▶│ Cache │
│ Layer │ │ (Redis) │
└──────┬──────┘ └─────────────┘
│
▼
┌─────────────┐
│ PostHog │
│ Client │
└──────┬──────┘
│
▼
┌─────────────┐
│ PostHog │
│ API │
└─────────────┘用户请求
│
▼
┌─────────────┐
│ API │
│ 网关 │
└──────┬──────┘
│
▼
┌─────────────┐ ┌─────────────┐
│ 服务层 │───▶│ 缓存 │
│ │ │ (Redis) │
└──────┬──────┘ └─────────────┘
│
▼
┌─────────────┐
│ PostHog │
│ 客户端 │
└──────┬──────┘
│
▼
┌─────────────┐
│ PostHog │
│ API │
└─────────────┘Configuration Management
配置管理
typescript
// config/posthog.ts
export interface PostHogConfig {
apiKey: string;
environment: 'development' | 'staging' | 'production';
timeout: number;
retries: number;
cache: {
enabled: boolean;
ttlSeconds: number;
};
}
export function loadPostHogConfig(): PostHogConfig {
const env = process.env.NODE_ENV || 'development';
return require(`./posthog.${env}.json`);
}typescript
// config/posthog.ts
export interface PostHogConfig {
apiKey: string;
environment: 'development' | 'staging' | 'production';
timeout: number;
retries: number;
cache: {
enabled: boolean;
ttlSeconds: number;
};
}
export function loadPostHogConfig(): PostHogConfig {
const env = process.env.NODE_ENV || 'development';
return require(`./posthog.${env}.json`);
}Instructions
实施步骤
Step 1: Create Directory Structure
步骤1:创建目录结构
Set up the project layout following the reference structure above.
按照上述参考结构搭建项目布局。
Step 2: Implement Client Wrapper
步骤2:实现客户端封装
Create the singleton client with caching and monitoring.
创建带有缓存和监控功能的单例客户端。
Step 3: Add Error Handling
步骤3:添加错误处理
Implement custom error classes for PostHog operations.
为PostHog操作实现自定义错误类。
Step 4: Configure Health Checks
步骤4:配置健康检查
Add health check endpoint for PostHog connectivity.
添加用于检测PostHog连通性的健康检查端点。
Output
交付成果
- Structured project layout
- Client wrapper with caching
- Error boundary implemented
- Health checks configured
- 结构化的项目布局
- 带有缓存功能的客户端封装
- 已实现的错误边界
- 已配置的健康检查
Error Handling
错误处理
| Issue | Cause | Solution |
|---|---|---|
| Circular dependencies | Wrong layering | Separate concerns by layer |
| Config not loading | Wrong paths | Verify config file locations |
| Type errors | Missing types | Add PostHog types |
| Test isolation | Shared state | Use dependency injection |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 循环依赖 | 分层错误 | 按层分离关注点 |
| 配置加载失败 | 路径错误 | 验证配置文件位置 |
| 类型错误 | 缺少类型定义 | 添加PostHog类型 |
| 测试隔离问题 | 共享状态 | 使用依赖注入 |
Examples
示例
Quick Setup Script
快速搭建脚本
bash
undefinedbash
undefinedCreate reference structure
创建参考结构
mkdir -p src/posthog/{handlers} src/services/posthog src/api/posthog
touch src/posthog/{client,config,types,errors}.ts
touch src/services/posthog/{index,sync,cache}.ts
undefinedmkdir -p src/posthog/{handlers} src/services/posthog src/api/posthog
touch src/posthog/{client,config,types,errors}.ts
touch src/services/posthog/{index,sync,cache}.ts
undefinedResources
参考资源
Flagship Skills
核心技能扩展
For multi-environment setup, see .
posthog-multi-env-setup如需多环境搭建指导,请查看。
posthog-multi-env-setup