# 持久层扩展开发指南

## 1. 概述

本文档旨在指导开发者如何扩展和集成自定义持久层适配器到系统中，以支持不同的存储类型，包括但不限于文件系统、内存存储、分布式存储等。系统采用了灵活的插件架构，允许通过标准化接口轻松扩展持久化能力。

## 2. 核心概念

### 2.1 存储接口 (StorageAdapter)

`StorageAdapter` 是所有持久层适配器必须实现的核心接口，定义了统一的数据操作方法：

```typescript
interface StorageAdapter {
  /**
   * 初始化存储适配器
   */
  initialize(): Promise<void>;
  
  /**
   * 关闭存储适配器并释放资源
   */
  close(): Promise<void>;
  
  /**
   * 创建新文档
   */
  create(collection: string, data: any): Promise<any>;
  
  /**
   * 查找文档列表
   */
  find<T>(collection: string, condition?: QueryCondition, offset?: number, limit?: number, sort?: SortOption): Promise<{ data: T[], total: number }>;
  
  /**
   * 根据ID查找单个文档
   */
  findById<T>(collection: string, id: string): Promise<T | null>;
  
  /**
   * 更新文档
   */
  update(collection: string, id: string, data: any): Promise<any>;
  
  /**
   * 替换整个文档
   */
  replace(collection: string, id: string, data: any): Promise<any>;
  
  /**
   * 删除文档
   */
  delete(collection: string, id: string): Promise<void>;
  
  /**
   * 批量删除文档
   */
  deleteMany(collection: string, condition: QueryCondition): Promise<number>;
  
  /**
   * 批量创建文档
   */
  insertMany(collection: string, dataArray: any[]): Promise<any[]>;
  
  /**
   * 执行事务操作
   */
  transaction<T>(callback: () => Promise<T>): Promise<T>;
}
```

### 2.2 查询条件 (QueryCondition)

`QueryCondition` 接口定义了标准的查询条件格式，支持多种操作符：

```typescript
interface QueryCondition {
  [key: string]: any | ConditionOperator;
}

interface ConditionOperator {
  /** 等于 */
  $eq?: any;
  /** 不等于 */
  $ne?: any;
  /** 大于 */
  $gt?: number;
  /** 大于等于 */
  $gte?: number;
  /** 小于 */
  $lt?: number;
  /** 小于等于 */
  $lte?: number;
  /** 包含在数组中 */
  $in?: any[];
  /** 不包含在数组中 */
  $nin?: any[];
  /** 包含指定字符串 */
  $like?: string;
  /** 正则匹配 */
  $regex?: string;
  /** 字段存在 */
  $exists?: boolean;
}
```

### 2.3 排序选项 (SortOption)

`SortOption` 接口定义了排序规则：

```typescript
interface SortOption {
  [field: string]: 1 | -1; // 1表示升序，-1表示降序
}
```

### 2.4 存储配置 (StorageConfig)

`StorageConfig` 是存储适配器配置的基础接口，不同的适配器可以扩展特定配置：

```typescript
interface StorageConfig {
  /** 存储类型名称 */
  storageType: string;
  /** 可选配置项 */
  [key: string]: any;
}
```

## 3. 开发自定义存储适配器

### 3.1 创建适配器类

要创建自定义存储适配器，需要实现 `StorageAdapter` 接口：

```typescript
import { StorageAdapter, QueryCondition, SortOption } from '../src/interfaces/StorageAdapter';

// 定义适配器特定配置
interface CustomStorageConfig {
  endpoint: string;
  apiKey?: string;
  timeout?: number;
}

// 实现自定义适配器类
class CustomStorageAdapter implements StorageAdapter {
  private config: CustomStorageConfig;
  private isInitialized: boolean = false;
  
  constructor(config: CustomStorageConfig) {
    this.config = config;
  }
  
  async initialize(): Promise<void> {
    // 实现初始化逻辑，如连接到存储服务
    console.log(`Initializing custom storage adapter with endpoint: ${this.config.endpoint}`);
    this.isInitialized = true;
  }
  
  async close(): Promise<void> {
    // 实现清理资源逻辑
    if (this.isInitialized) {
      console.log('Closing custom storage adapter');
      this.isInitialized = false;
    }
  }
  
  async create(collection: string, data: any): Promise<any> {
    // 实现创建文档的逻辑
    // ...
  }
  
  async find<T>(collection: string, condition?: QueryCondition, offset: number = 0, limit: number = 100, sort?: SortOption): Promise<{ data: T[], total: number }> {
    // 实现查找文档列表的逻辑
    // ...
  }
  
  // 实现其他接口方法...
  async findById<T>(collection: string, id: string): Promise<T | null> { /* ... */ }
  async update(collection: string, id: string, data: any): Promise<any> { /* ... */ }
  async replace(collection: string, id: string, data: any): Promise<any> { /* ... */ }
  async delete(collection: string, id: string): Promise<void> { /* ... */ }
  async deleteMany(collection: string, condition: QueryCondition): Promise<number> { /* ... */ }
  async insertMany(collection: string, dataArray: any[]): Promise<any[]> { /* ... */ }
  async transaction<T>(callback: () => Promise<T>): Promise<T> { /* ... */ }
}
```

### 3.2 实现查询和排序逻辑

在自定义适配器中实现查询和排序功能时，需要处理以下几点：

1. 解析查询条件，转换为适配器特有的查询格式
2. 处理排序规则
3. 实现分页功能
4. 返回统一格式的结果

```typescript
async find<T>(collection: string, condition?: QueryCondition, offset: number = 0, limit: number = 100, sort?: SortOption): Promise<{ data: T[], total: number }> {
  // 确保已初始化
  if (!this.isInitialized) {
    throw new Error('Adapter not initialized');
  }
  
  try {
    // 转换查询条件为适配器特定格式
    const nativeQuery = this.convertToNativeQuery(condition || {});
    
    // 获取符合条件的总记录数
    const total = await this.getTotalCount(collection, nativeQuery);
    
    // 应用排序
    if (sort) {
      nativeQuery.sort = this.convertToNativeSort(sort);
    }
    
    // 应用分页
    nativeQuery.skip = offset;
    nativeQuery.limit = limit;
    
    // 执行查询
    const results = await this.executeNativeQuery<T>(collection, nativeQuery);
    
    return {
      data: results,
      total
    };
  } catch (error) {
    console.error('Error in find operation:', error);
    throw error;
  }
}

// 辅助方法，将标准查询条件转换为适配器特定查询格式
private convertToNativeQuery(condition: QueryCondition): any {
  // 实现转换逻辑
  // ...
}
```

## 4. 开发存储插件

要使自定义适配器可供系统使用，需要创建一个存储插件：

```typescript
import { StoragePlugin, StorageAdapter, StorageConfig } from '../src/interfaces/StoragePlugin';
import { CustomStorageAdapter } from './CustomStorageAdapter';

// 定义插件元数据
const pluginMetadata = {
  name: 'custom-storage-plugin',
  version: '1.0.0',
  description: 'Custom storage plugin implementation',
};

class CustomStoragePlugin implements StoragePlugin {
  getMetadata(): any {
    return pluginMetadata;
  }
  
  initialize(): void {
    // 可以在此处初始化插件所需的资源
    console.log('Custom storage plugin initialized');
  }
  
  createAdapter(config: StorageConfig): StorageAdapter {
    // 验证配置
    if (!config.endpoint) {
      throw new Error('Custom storage requires endpoint configuration');
    }
    
    // 创建并返回适配器实例
    return new CustomStorageAdapter(config);
  }
  
  getSupportedTypes(): string[] {
    // 返回此插件支持的存储类型
    return ['custom', 'custom-storage'];
  }
}

export { CustomStoragePlugin };
```

## 5. 注册和使用自定义适配器

### 5.1 注册存储插件

有两种方式注册自定义存储插件：

#### 5.1.1 直接注册

```typescript
import { StorageRegistry } from '../src/registry/StorageRegistry';
import { CustomStoragePlugin } from './CustomStoragePlugin';

// 创建并注册插件
const customPlugin = new CustomStoragePlugin();
customPlugin.initialize();

// 注册到存储注册表
StorageRegistry.registerPlugin(customPlugin);
```

#### 5.1.2 通过配置自动加载

将插件路径添加到系统配置中：

```typescript
const systemConfig = {
  storagePlugins: [
    './path/to/CustomStoragePlugin',
    './another/path/AnotherStoragePlugin'
  ]
};

// 然后在系统启动时自动加载
```

### 5.2 使用自定义适配器

一旦插件注册成功，就可以通过 `StorageFactory` 创建和使用自定义适配器：

```typescript
import { StorageFactory } from '../src/factories/StorageFactory';

// 创建自定义存储适配器
const adapter = StorageFactory.create('custom', {
  endpoint: 'https://api.example.com/storage',
  apiKey: 'your-api-key',
  timeout: 5000
});

// 初始化适配器
await adapter.initialize();

// 使用适配器进行数据操作
const result = await adapter.create('users', {
  name: 'John Doe',
  email: 'john@example.com'
});

// 执行查询
const users = await adapter.find('users', { active: true });

// 使用完成后关闭适配器
await adapter.close();
```

## 6. 与 DomainManager 集成

自定义存储适配器可以通过 `DomainManagerFactory` 与领域管理器集成：

```typescript
import { DomainManagerFactory } from '../src/factories/DomainManagerFactory';

// 从配置创建领域管理器
const domainManager = await DomainManagerFactory.createFromConfig({
  persistence: {
    storageType: 'custom',
    storageConfig: {
      endpoint: 'https://api.example.com/storage',
      apiKey: 'your-api-key'
    },
    enableCache: true,
    cacheConfig: {
      ttl: 3600
    }
  }
});

// 使用领域管理器
const userDomain = domainManager.getDomain('user');
const newUser = await userDomain.create({
  name: 'Jane Doe',
  email: 'jane@example.com'
});
```

## 7. 测试自定义适配器

为确保自定义适配器的正确性，应该编写全面的测试：

```typescript
import { CustomStorageAdapter } from './CustomStorageAdapter';

describe('CustomStorageAdapter', () => {
  let adapter: CustomStorageAdapter;
  
  beforeAll(async () => {
    adapter = new CustomStorageAdapter({
      endpoint: 'https://api.example.com/test-storage'
    });
    await adapter.initialize();
  });
  
  afterAll(async () => {
    await adapter.close();
  });
  
  test('should create and retrieve documents', async () => {
    // 创建测试文档
    const createdDoc = await adapter.create('testCollection', {
      testField: 'testValue'
    });
    
    // 验证文档创建
    expect(createdDoc).toBeDefined();
    expect(createdDoc.id).toBeDefined();
    
    // 根据ID查找文档
    const retrievedDoc = await adapter.findById('testCollection', createdDoc.id);
    
    // 验证检索结果
    expect(retrievedDoc).toBeDefined();
    expect(retrievedDoc?.testField).toBe('testValue');
  });
  
  // 添加更多测试用例...
});
```

## 8. 最佳实践

### 8.1 错误处理

- 所有适配器方法应实现适当的错误处理
- 应记录详细的错误信息，但避免泄露敏感信息
- 对于网络相关操作，应实现超时和重试机制

### 8.2 性能优化

- 实现查询结果缓存以提高性能
- 优化批量操作，减少网络请求或I/O操作
- 对大数据集实现有效的分页和流式处理

### 8.3 资源管理

- 在 `initialize` 方法中申请资源，在 `close` 方法中释放资源
- 实现 `close` 方法以确保在系统关闭时正确清理资源
- 使用连接池管理与外部存储服务的连接

### 8.4 事务支持

- 如果底层存储支持事务，应实现完整的事务语义
- 对于不支持事务的存储，可以实现模拟事务或提供适当的警告

## 9. 现有适配器示例

系统内置了以下适配器示例，可作为开发参考：

### 9.1 内存存储适配器 (MemoryStorageAdapter)

适用于测试和开发环境的轻量级内存存储实现。

**配置选项：**
- `ttl`: 可选，文档过期时间（毫秒）
- `autoCleanupInterval`: 可选，自动清理过期文档的间隔时间（毫秒）

### 9.2 文件系统存储适配器 (FileSystemStorageAdapter)

将数据持久化到文件系统的适配器实现。

**配置选项：**
- `rootDir`: 必需，根目录路径
- `prettyPrint`: 可选，是否美化JSON输出
- `syncInterval`: 可选，数据同步间隔（毫秒）

## 10. 故障排除

### 10.1 常见问题

- **适配器初始化失败**：检查配置参数是否正确，以及是否有权限访问存储资源
- **查询结果不正确**：确保查询条件转换逻辑正确，特别是操作符映射
- **性能问题**：考虑实现结果缓存，优化批量操作，或调整分页参数

### 10.2 日志和调试

- 在关键操作点添加详细日志，帮助跟踪问题
- 实现适配器级别的调试模式，提供额外的诊断信息
- 使用性能监控工具识别瓶颈

## 11. 总结

本指南提供了开发和集成自定义持久层适配器的完整流程。通过遵循这些步骤，可以轻松扩展系统的存储能力，支持各种存储类型和技术，同时保持系统的一致性和可维护性。

如果有任何问题或建议，请联系开发团队。

---

*最后更新日期：2023年10月*