什么是抽象层?
这个例子里 抽象层(abstraction layer)的意思可以从两个角度来理解:
1. 从软件设计的角度
抽象层是指把「共性逻辑」抽取出来,屏蔽底层的复杂性,对外提供统一的调用接口。
它的作用就是:
- 隐藏实现细节(比如你用的
CloudBaseAdapter里具体怎么调云数据库,外部根本不需要关心)。 - 统一入口(所有的
create / update / delete等操作,都通过BaseService调用,而不是直接操作数据库)。 - 允许扩展(子类只需要实现差异化的逻辑,比如
collectionName和getValidationRules(),其他通用流程都复用)。
所以,这个 BaseService 就是一个典型的抽象层。
上层业务代码只和 UserService / OrderService 交互,而不用去管数据库 SDK 或校验逻辑的细节。
2. 结合这段代码来看
在 BaseService 里,你做了几个关键的抽象:
-
数据库操作的抽象
cloudAdapter.create(...)/update(...)/list(...)- 上层并不需要知道数据库是 CloudBase 还是 MySQL,反正就是 CRUD 接口。
-
通用流程的抽象
-
例如
create的流程:校验 → 数据预处理(beforeCreate)→ 执行数据库操作 → 后处理(afterCreate)。
-
这些流程写在基类里,子类只需“填空”(重写钩子)。
-
-
可变逻辑的抽象
- 通过
abstract getValidationRules()让子类去定义校验规则。 - 通过钩子方法(
beforeCreate、afterUpdate)让子类自定义扩展。
- 通过
换句话说,你把所有数据库相关的“共性逻辑”封装进了 **BaseService**,业务层的 **UserService**、**ProductService**** 只需关心自己的规则和数据模型**。
3. 一个形象的比喻
-
你现在写的
BaseService就像 汽车的底盘。- 底盘提供了「发动机、刹车、方向盘」这些通用能力(CRUD、验证、错误处理)。
- 不管你造的是「小轿车」还是「卡车」(UserService、OrderService),都不需要重新造底盘,只要加上「壳子和配置」(collectionName、校验规则)就能跑。
例子
// src/services/base/BaseService.ts export abstract class BaseService<T extends { _id?: string }> { protected abstract collectionName: string; protected cloudAdapter: CloudBaseAdapter; protected validator: ValidationService; protected errorHandler: ErrorHandler;
constructor() { this.cloudAdapter = new CloudBaseAdapter(); this.validator = new ValidationService(); this.errorHandler = new ErrorHandler(); }
// 🔹 核心 CRUD 操作 async create(data: Omit<T, '_id'>): Promise { try { // 1. 数据验证 await this.validator.validateCreate(data, this.getValidationRules());
// 2. 预处理数据
const processedData = await this.beforeCreate(data);
// 3. 执行创建
const result = await this.cloudAdapter.create(this.collectionName, processedData);
// 4. 后处理
await this.afterCreate(result);
return result;
} catch (error) {
throw this.errorHandler.handle(error, 'CREATE_FAILED');
}
}
async getById(id: string): Promise<T | null> { try { const result = await this.cloudAdapter.getById(this.collectionName, id); return result ? await this.afterGet(result) : null; } catch (error) { throw this.errorHandler.handle(error, 'GET_FAILED'); } }
async update(id: string, data: Partial): Promise { try { await this.validator.validateUpdate(data, this.getValidationRules()); const processedData = await this.beforeUpdate(id, data); const result = await this.cloudAdapter.update(this.collectionName, id, processedData); await this.afterUpdate(result); return result; } catch (error) { throw this.errorHandler.handle(error, 'UPDATE_FAILED'); } }
async delete(id: string): Promise { try { await this.beforeDelete(id); const result = await this.cloudAdapter.delete(this.collectionName, id); await this.afterDelete(id); return result; } catch (error) { throw this.errorHandler.handle(error, 'DELETE_FAILED'); } }
// 🔹 高级查询操作 async list(options: ListOptions = {}): Promise<PaginatedResult> { try { const { filters, pagination, sorting } = options; return await this.cloudAdapter.list( this.collectionName, filters, pagination, sorting ); } catch (error) { throw this.errorHandler.handle(error, 'LIST_FAILED'); } }
async count(filters?: any): Promise { return await this.cloudAdapter.count(this.collectionName, filters); }
// 🔹 批量操作 async batchCreate(items: Omit<T, '_id'>[]): Promise<T[]> { try { const validatedItems = await Promise.all( items.map(item => this.validator.validateCreate(item, this.getValidationRules())) ); return await this.cloudAdapter.batchCreate(this.collectionName, validatedItems); } catch (error) { throw this.errorHandler.handle(error, 'BATCH_CREATE_FAILED'); } }
async batchUpdate(updates: Array<{id: string, data: Partial}>): Promise<T[]> { try { return await this.cloudAdapter.batchUpdate(this.collectionName, updates); } catch (error) { throw this.errorHandler.handle(error, 'BATCH_UPDATE_FAILED'); } }
// 🔹 软删除支持 async softDelete(id: string): Promise { return await this.update(id, { deleted_at: new Date().toISOString(), is_active: false } as Partial); }
async restore(id: string): Promise { return await this.update(id, { deleted_at: null, is_active: true } as Partial); }
// 🔹 钩子方法(子类可重写) protected async beforeCreate(data: any): Promise { return { ...data, created_at: new Date().toISOString(), updated_at: new Date().toISOString() }; }
protected async afterCreate(result: T): Promise { // 子类可重写,如发送通知、更新缓存等 }
protected async beforeUpdate(id: string, data: any): Promise { return { ...data, updated_at: new Date().toISOString() }; }
protected async afterUpdate(result: T): Promise { // 子类可重写 }
protected async beforeDelete(id: string): Promise { // 子类可重写,如检查关联数据 }
protected async afterDelete(id: string): Promise { // 子类可重写 }
protected async afterGet(result: T): Promise { // 子类可重写,如数据转换 return result; }
// 🔹 抽象方法(子类必须实现) protected abstract getValidationRules(): ValidationRules; }