generic-crud.service.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import { DataSource, Repository, ObjectLiteral, DeepPartial, In } from 'typeorm';
  2. import { z } from '@hono/zod-openapi';
  3. import { DataPermissionOptions, validateDataPermissionOptions } from '../types/data-permission.types';
  4. export abstract class GenericCrudService<T extends ObjectLiteral> {
  5. protected repository: Repository<T>;
  6. private userTrackingOptions?: UserTrackingOptions;
  7. private dataPermissionOptions?: DataPermissionOptions;
  8. protected relationFields?: RelationFieldOptions;
  9. constructor(
  10. protected dataSource: DataSource,
  11. protected entity: new () => T,
  12. options?: {
  13. userTracking?: UserTrackingOptions;
  14. relationFields?: RelationFieldOptions;
  15. dataPermission?: DataPermissionOptions;
  16. }
  17. ) {
  18. this.repository = this.dataSource.getRepository(entity);
  19. this.userTrackingOptions = options?.userTracking;
  20. this.relationFields = options?.relationFields;
  21. // 验证并设置数据权限配置
  22. if (options?.dataPermission) {
  23. validateDataPermissionOptions(options.dataPermission);
  24. this.dataPermissionOptions = options.dataPermission;
  25. }
  26. }
  27. /**
  28. * 获取分页列表
  29. */
  30. async getList(
  31. page: number = 1,
  32. pageSize: number = 10,
  33. keyword?: string,
  34. searchFields?: string[],
  35. where?: Partial<T>,
  36. relations: string[] = [],
  37. order: { [P in keyof T]?: 'ASC' | 'DESC' } = {},
  38. filters?: {
  39. [key: string]: any;
  40. },
  41. userId?: string | number
  42. ): Promise<[T[], number]> {
  43. const skip = (page - 1) * pageSize;
  44. const query = this.repository.createQueryBuilder('entity');
  45. // 添加数据权限过滤
  46. if (this.dataPermissionOptions?.enabled && userId) {
  47. const userIdField = this.dataPermissionOptions.userIdField;
  48. query.andWhere(`entity.${userIdField} = :userId`, { userId });
  49. }
  50. // 添加关联关系(支持嵌套关联,如 ['contract.client'])
  51. // 使用一致的别名生成策略,确保搜索时能正确引用关联字段
  52. if (relations.length > 0) {
  53. relations.forEach((relation) => {
  54. const parts = relation.split('.');
  55. let currentAlias = 'entity';
  56. parts.forEach((part, index) => {
  57. // 生成一致的别名:对于嵌套关联,使用下划线连接路径
  58. const newAlias = index === 0 ? part : parts.slice(0, index + 1).join('_');
  59. query.leftJoinAndSelect(`${currentAlias}.${part}`, newAlias);
  60. currentAlias = newAlias;
  61. });
  62. });
  63. }
  64. // 关键词搜索 - 支持关联字段搜索(格式:relation.field 或 relation.nestedRelation.field)
  65. if (keyword && searchFields && searchFields.length > 0) {
  66. const searchConditions: string[] = [];
  67. const searchParams: Record<string, string> = { keyword: `%${keyword}%` };
  68. searchFields.forEach((field) => {
  69. // 检查是否为关联字段(包含点号)
  70. if (field.includes('.')) {
  71. const parts = field.split('.');
  72. const alias = parts.slice(0, -1).join('_'); // 使用下划线连接关系路径作为别名
  73. const fieldName = parts[parts.length - 1];
  74. searchConditions.push(`${alias}.${fieldName} LIKE :keyword`);
  75. } else {
  76. // 普通字段搜索
  77. searchConditions.push(`entity.${field} LIKE :keyword`);
  78. }
  79. });
  80. if (searchConditions.length > 0) {
  81. query.andWhere(`(${searchConditions.join(' OR ')})`, searchParams);
  82. }
  83. }
  84. // 条件查询
  85. if (where) {
  86. Object.entries(where).forEach(([key, value]) => {
  87. if (value !== undefined && value !== null) {
  88. query.andWhere(`entity.${key} = :${key}`, { [key]: value });
  89. }
  90. });
  91. }
  92. // 扩展筛选条件
  93. if (filters) {
  94. Object.entries(filters).forEach(([key, value]) => {
  95. if (value !== undefined && value !== null && value !== '') {
  96. const fieldName = key.startsWith('_') ? key.substring(1) : key;
  97. // 检查是否为关联字段(包含点号)
  98. let tableAlias: string = 'entity';
  99. let actualFieldName: string = fieldName;
  100. if (fieldName.includes('.')) {
  101. const parts = fieldName.split('.');
  102. tableAlias = parts.slice(0, -1).join('_') || 'entity'; // 使用下划线连接关系路径作为别名
  103. actualFieldName = parts[parts.length - 1] || fieldName;
  104. }
  105. // 支持不同类型的筛选
  106. if (Array.isArray(value)) {
  107. // 数组类型:IN查询
  108. if (value.length > 0) {
  109. query.andWhere(`${tableAlias}.${actualFieldName} IN (:...${key})`, { [key]: value });
  110. }
  111. } else if (typeof value === 'string' && value.includes('%')) {
  112. // 模糊匹配
  113. query.andWhere(`${tableAlias}.${actualFieldName} LIKE :${key}`, { [key]: value });
  114. } else if (typeof value === 'object' && value !== null) {
  115. // 范围查询
  116. if ('gte' in value) {
  117. query.andWhere(`${tableAlias}.${actualFieldName} >= :${key}_gte`, { [`${key}_gte`]: value.gte });
  118. }
  119. if ('gt' in value) {
  120. query.andWhere(`${tableAlias}.${actualFieldName} > :${key}_gt`, { [`${key}_gt`]: value.gt });
  121. }
  122. if ('lte' in value) {
  123. query.andWhere(`${tableAlias}.${actualFieldName} <= :${key}_lte`, { [`${key}_lte`]: value.lte });
  124. }
  125. if ('lt' in value) {
  126. query.andWhere(`${tableAlias}.${actualFieldName} < :${key}_lt`, { [`${key}_lt`]: value.lt });
  127. }
  128. if ('between' in value && Array.isArray(value.between) && value.between.length === 2) {
  129. query.andWhere(`${tableAlias}.${actualFieldName} BETWEEN :${key}_start AND :${key}_end`, {
  130. [`${key}_start`]: value.between[0],
  131. [`${key}_end`]: value.between[1]
  132. });
  133. }
  134. } else {
  135. // 精确匹配
  136. query.andWhere(`${tableAlias}.${actualFieldName} = :${key}`, { [key]: value });
  137. }
  138. }
  139. });
  140. }
  141. // 排序
  142. Object.entries(order).forEach(([key, direction]) => {
  143. query.orderBy(`entity.${key}`, direction);
  144. });
  145. const finalQuery = query.skip(skip).take(pageSize);
  146. // console.log(finalQuery.getSql())
  147. return finalQuery.getManyAndCount();
  148. }
  149. /**
  150. * 根据ID获取单个实体
  151. */
  152. async getById(id: number, relations: string[] = [], userId?: string | number): Promise<T | null> {
  153. const entity = await this.repository.findOne({
  154. where: { id } as any,
  155. relations
  156. });
  157. // 数据权限验证
  158. if (entity && this.dataPermissionOptions?.enabled && userId) {
  159. const hasPermission = await this.checkPermission(entity, userId);
  160. if (!hasPermission) {
  161. return null; // 没有权限返回null
  162. }
  163. }
  164. return entity;
  165. }
  166. /**
  167. * 检查用户对实体的权限
  168. */
  169. private async checkPermission(entity: any, userId: string | number): Promise<boolean> {
  170. const options = this.dataPermissionOptions;
  171. if (!options?.enabled) return true;
  172. // 管理员权限覆盖检查
  173. if (options.adminOverride?.enabled && options.adminOverride.adminRole) {
  174. // 这里需要从认证系统获取用户角色信息
  175. // 暂时假设管理员可以访问所有数据
  176. // 实际实现中需要集成用户角色检查
  177. const isAdmin = await this.checkAdminRole(userId, options.adminOverride.adminRole);
  178. if (isAdmin) {
  179. return true;
  180. }
  181. }
  182. // 自定义权限验证器
  183. if (options.customValidator) {
  184. return await options.customValidator(userId, entity);
  185. }
  186. // 基础权限验证:用户ID字段匹配
  187. const userIdField = options.userIdField;
  188. const entityUserId = entity[userIdField];
  189. return entityUserId === userId;
  190. }
  191. /**
  192. * 检查用户是否为管理员
  193. * TODO: 需要集成实际的用户角色检查
  194. */
  195. private async checkAdminRole(userId: string | number, adminRole: string): Promise<boolean> {
  196. // 这里需要从认证系统获取用户角色信息
  197. // 暂时返回false,实际实现中需要集成用户角色检查
  198. return false;
  199. }
  200. /**
  201. * 设置用户跟踪字段
  202. */
  203. private setUserFields(data: any, userId?: string | number, isCreate: boolean = true): void {
  204. if (!this.userTrackingOptions || !userId) {
  205. return;
  206. }
  207. const {
  208. createdByField = 'createdBy',
  209. updatedByField = 'updatedBy',
  210. userIdField = 'userId'
  211. } = this.userTrackingOptions;
  212. // 设置创建人
  213. // 只有在数据中不存在该字段时才设置,避免覆盖管理员传入的用户ID
  214. if (isCreate && createdByField && !data[createdByField]) {
  215. data[createdByField] = userId;
  216. }
  217. // 设置更新人
  218. if (updatedByField) {
  219. data[updatedByField] = userId;
  220. }
  221. // 设置关联的用户ID(如userId字段)
  222. // 只有在数据中不存在该字段时才设置,避免覆盖管理员传入的用户ID
  223. if (isCreate && userIdField && !data[userIdField]) {
  224. data[userIdField] = userId;
  225. }
  226. }
  227. /**
  228. * 处理关联字段
  229. */
  230. private async handleRelationFields(data: any, entity: T, _isUpdate: boolean = false): Promise<void> {
  231. if (!this.relationFields) return;
  232. for (const [fieldName, config] of Object.entries(this.relationFields)) {
  233. if (data[fieldName] !== undefined) {
  234. const ids = data[fieldName];
  235. const relationRepository = this.dataSource.getRepository(config.targetEntity);
  236. if (ids && Array.isArray(ids) && ids.length > 0) {
  237. const relatedEntities = await relationRepository.findBy({ id: In(ids) });
  238. (entity as any)[config.relationName] = relatedEntities;
  239. } else {
  240. (entity as any)[config.relationName] = [];
  241. }
  242. // 清理原始数据中的关联字段
  243. delete data[fieldName];
  244. }
  245. }
  246. }
  247. /**
  248. * 创建实体
  249. */
  250. async create(data: DeepPartial<T>, userId?: string | number): Promise<T> {
  251. // 权限验证:防止用户创建不属于自己的数据
  252. if (this.dataPermissionOptions?.enabled && userId) {
  253. const userIdField = this.dataPermissionOptions.userIdField;
  254. // 如果数据中已经包含用户ID字段,验证是否与当前用户匹配
  255. const dataObj = data as any;
  256. if (dataObj[userIdField] && dataObj[userIdField] !== userId) {
  257. throw new Error('无权创建该资源');
  258. }
  259. }
  260. const entityData = { ...data };
  261. this.setUserFields(entityData, userId, true);
  262. // 分离关联字段数据
  263. const relationData: any = {};
  264. if (this.relationFields) {
  265. for (const fieldName of Object.keys(this.relationFields)) {
  266. if (fieldName in entityData) {
  267. relationData[fieldName] = (entityData as any)[fieldName];
  268. delete (entityData as any)[fieldName];
  269. }
  270. }
  271. }
  272. const entity = this.repository.create(entityData as DeepPartial<T>);
  273. // 处理关联字段
  274. await this.handleRelationFields(relationData, entity);
  275. return this.repository.save(entity);
  276. }
  277. /**
  278. * 更新实体
  279. */
  280. async update(id: number, data: Partial<T>, userId?: string | number): Promise<T | null> {
  281. // 权限验证
  282. if (this.dataPermissionOptions?.enabled && userId) {
  283. const entity = await this.getById(id);
  284. if (!entity) return null;
  285. const hasPermission = await this.checkPermission(entity, userId);
  286. if (!hasPermission) {
  287. throw new Error('无权更新该资源');
  288. }
  289. }
  290. const updateData = { ...data };
  291. this.setUserFields(updateData, userId, false);
  292. // 分离关联字段数据
  293. const relationData: any = {};
  294. if (this.relationFields) {
  295. for (const fieldName of Object.keys(this.relationFields)) {
  296. if (fieldName in updateData) {
  297. relationData[fieldName] = (updateData as any)[fieldName];
  298. delete (updateData as any)[fieldName];
  299. }
  300. }
  301. }
  302. // 先更新基础字段
  303. await this.repository.update(id, updateData);
  304. // 获取完整实体并处理关联字段
  305. const entity = await this.getById(id);
  306. if (!entity) return null;
  307. // 处理关联字段
  308. await this.handleRelationFields(relationData, entity, true);
  309. return this.repository.save(entity);
  310. }
  311. /**
  312. * 删除实体
  313. */
  314. async delete(id: number, userId?: string | number): Promise<boolean> {
  315. // 权限验证
  316. if (this.dataPermissionOptions?.enabled && userId) {
  317. const entity = await this.getById(id);
  318. if (!entity) return false;
  319. const hasPermission = await this.checkPermission(entity, userId);
  320. if (!hasPermission) {
  321. throw new Error('无权删除该资源');
  322. }
  323. }
  324. // 执行删除
  325. const result = await this.repository.delete(id);
  326. return result.affected === 1;
  327. }
  328. /**
  329. * 高级查询方法
  330. */
  331. createQueryBuilder(alias: string = 'entity') {
  332. return this.repository.createQueryBuilder(alias);
  333. }
  334. }
  335. export interface UserTrackingOptions {
  336. createdByField?: string;
  337. updatedByField?: string;
  338. userIdField?: string;
  339. }
  340. export interface RelationFieldOptions {
  341. [fieldName: string]: {
  342. relationName: string;
  343. targetEntity: new () => any;
  344. joinTableName?: string;
  345. };
  346. }
  347. export type CrudOptions<
  348. T extends ObjectLiteral,
  349. CreateSchema extends z.ZodSchema = z.ZodSchema,
  350. UpdateSchema extends z.ZodSchema = z.ZodSchema,
  351. GetSchema extends z.ZodSchema = z.ZodSchema,
  352. ListSchema extends z.ZodSchema = z.ZodSchema
  353. > = {
  354. entity: new () => T;
  355. createSchema: CreateSchema;
  356. updateSchema: UpdateSchema;
  357. getSchema: GetSchema;
  358. listSchema: ListSchema;
  359. searchFields?: string[];
  360. relations?: string[];
  361. middleware?: any[];
  362. userTracking?: UserTrackingOptions;
  363. relationFields?: RelationFieldOptions;
  364. readOnly?: boolean;
  365. /**
  366. * 数据权限控制配置
  367. */
  368. dataPermission?: DataPermissionOptions;
  369. };