generic-crud.service.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import { DataSource, Repository, ObjectLiteral, DeepPartial, In } from 'typeorm';
  2. import { z } from '@hono/zod-openapi';
  3. export abstract class GenericCrudService<T extends ObjectLiteral> {
  4. protected repository: Repository<T>;
  5. private userTrackingOptions?: UserTrackingOptions;
  6. protected relationFields?: RelationFieldOptions;
  7. constructor(
  8. protected dataSource: DataSource,
  9. protected entity: new () => T,
  10. options?: {
  11. userTracking?: UserTrackingOptions;
  12. relationFields?: RelationFieldOptions;
  13. }
  14. ) {
  15. this.repository = this.dataSource.getRepository(entity);
  16. this.userTrackingOptions = options?.userTracking;
  17. this.relationFields = options?.relationFields;
  18. }
  19. /**
  20. * 获取分页列表
  21. */
  22. async getList(
  23. page: number = 1,
  24. pageSize: number = 10,
  25. keyword?: string,
  26. searchFields?: string[],
  27. where?: Partial<T>,
  28. relations: string[] = [],
  29. order: { [P in keyof T]?: 'ASC' | 'DESC' } = {},
  30. filters?: {
  31. [key: string]: any;
  32. }
  33. ): Promise<[T[], number]> {
  34. const skip = (page - 1) * pageSize;
  35. const query = this.repository.createQueryBuilder('entity');
  36. // 添加关联关系(支持嵌套关联,如 ['contract.client'])
  37. // 使用一致的别名生成策略,确保搜索时能正确引用关联字段
  38. if (relations.length > 0) {
  39. relations.forEach((relation) => {
  40. const parts = relation.split('.');
  41. let currentAlias = 'entity';
  42. parts.forEach((part, index) => {
  43. // 生成一致的别名:对于嵌套关联,使用下划线连接路径
  44. const newAlias = index === 0 ? part : parts.slice(0, index + 1).join('_');
  45. query.leftJoinAndSelect(`${currentAlias}.${part}`, newAlias);
  46. currentAlias = newAlias;
  47. });
  48. });
  49. }
  50. // 关键词搜索 - 支持关联字段搜索(格式:relation.field 或 relation.nestedRelation.field)
  51. if (keyword && searchFields && searchFields.length > 0) {
  52. const searchConditions: string[] = [];
  53. const searchParams: Record<string, string> = { keyword: `%${keyword}%` };
  54. searchFields.forEach((field) => {
  55. // 检查是否为关联字段(包含点号)
  56. if (field.includes('.')) {
  57. const parts = field.split('.');
  58. // 对于单层关联(如 startLocation.name),别名就是关联名本身
  59. const alias = parts[0];
  60. const fieldName = parts[parts.length - 1];
  61. searchConditions.push(`${alias}.${fieldName} LIKE :keyword`);
  62. } else {
  63. // 普通字段搜索
  64. searchConditions.push(`entity.${field} LIKE :keyword`);
  65. }
  66. });
  67. if (searchConditions.length > 0) {
  68. query.andWhere(`(${searchConditions.join(' OR ')})`, searchParams);
  69. }
  70. }
  71. // 条件查询
  72. if (where) {
  73. Object.entries(where).forEach(([key, value]) => {
  74. if (value !== undefined && value !== null) {
  75. query.andWhere(`entity.${key} = :${key}`, { [key]: value });
  76. }
  77. });
  78. }
  79. // 扩展筛选条件
  80. if (filters) {
  81. Object.entries(filters).forEach(([key, value]) => {
  82. if (value !== undefined && value !== null && value !== '') {
  83. const fieldName = key.startsWith('_') ? key.substring(1) : key;
  84. // 检查是否为关联字段(包含点号)
  85. let tableAlias: string = 'entity';
  86. let actualFieldName: string = fieldName;
  87. if (fieldName.includes('.')) {
  88. const parts = fieldName.split('.');
  89. tableAlias = parts.slice(0, -1).join('_') || 'entity'; // 使用下划线连接关系路径作为别名
  90. actualFieldName = parts[parts.length - 1] || fieldName;
  91. }
  92. // 支持不同类型的筛选
  93. if (Array.isArray(value)) {
  94. // 数组类型:IN查询
  95. if (value.length > 0) {
  96. query.andWhere(`${tableAlias}.${actualFieldName} IN (:...${key})`, { [key]: value });
  97. }
  98. } else if (typeof value === 'string' && value.includes('%')) {
  99. // 模糊匹配
  100. query.andWhere(`${tableAlias}.${actualFieldName} LIKE :${key}`, { [key]: value });
  101. } else if (typeof value === 'object' && value !== null) {
  102. // 范围查询
  103. if ('gte' in value) {
  104. query.andWhere(`${tableAlias}.${actualFieldName} >= :${key}_gte`, { [`${key}_gte`]: value.gte });
  105. }
  106. if ('gt' in value) {
  107. query.andWhere(`${tableAlias}.${actualFieldName} > :${key}_gt`, { [`${key}_gt`]: value.gt });
  108. }
  109. if ('lte' in value) {
  110. query.andWhere(`${tableAlias}.${actualFieldName} <= :${key}_lte`, { [`${key}_lte`]: value.lte });
  111. }
  112. if ('lt' in value) {
  113. query.andWhere(`${tableAlias}.${actualFieldName} < :${key}_lt`, { [`${key}_lt`]: value.lt });
  114. }
  115. if ('between' in value && Array.isArray(value.between) && value.between.length === 2) {
  116. query.andWhere(`${tableAlias}.${actualFieldName} BETWEEN :${key}_start AND :${key}_end`, {
  117. [`${key}_start`]: value.between[0],
  118. [`${key}_end`]: value.between[1]
  119. });
  120. }
  121. } else {
  122. // 精确匹配
  123. query.andWhere(`${tableAlias}.${actualFieldName} = :${key}`, { [key]: value });
  124. }
  125. }
  126. });
  127. }
  128. // 排序
  129. Object.entries(order).forEach(([key, direction]) => {
  130. query.orderBy(`entity.${key}`, direction);
  131. });
  132. const finalQuery = query.skip(skip).take(pageSize);
  133. // console.debug('Generated SQL:', finalQuery.getSql())
  134. return finalQuery.getManyAndCount();
  135. }
  136. /**
  137. * 根据ID获取单个实体
  138. */
  139. async getById(id: number, relations: string[] = []): Promise<T | null> {
  140. return this.repository.findOne({
  141. where: { id } as any,
  142. relations
  143. });
  144. }
  145. /**
  146. * 设置用户跟踪字段
  147. */
  148. private setUserFields(data: any, userId?: string | number, isCreate: boolean = true): void {
  149. if (!this.userTrackingOptions || !userId) {
  150. return;
  151. }
  152. const {
  153. createdByField = 'createdBy',
  154. updatedByField = 'updatedBy',
  155. userIdField = 'userId'
  156. } = this.userTrackingOptions;
  157. // 设置创建人
  158. if (isCreate && createdByField) {
  159. data[createdByField] = userId;
  160. }
  161. // 设置更新人
  162. if (updatedByField) {
  163. data[updatedByField] = userId;
  164. }
  165. // 设置关联的用户ID(如userId字段)
  166. if (isCreate && userIdField) {
  167. data[userIdField] = userId;
  168. }
  169. }
  170. /**
  171. * 创建实体
  172. */
  173. /**
  174. * 处理关联字段
  175. */
  176. private async handleRelationFields(data: any, entity: T, _isUpdate: boolean = false): Promise<void> {
  177. if (!this.relationFields) return;
  178. for (const [fieldName, config] of Object.entries(this.relationFields)) {
  179. if (data[fieldName] !== undefined) {
  180. const ids = data[fieldName];
  181. const relationRepository = this.dataSource.getRepository(config.targetEntity);
  182. if (ids && Array.isArray(ids) && ids.length > 0) {
  183. const relatedEntities = await relationRepository.findBy({ id: In(ids) });
  184. (entity as any)[config.relationName] = relatedEntities;
  185. } else {
  186. (entity as any)[config.relationName] = [];
  187. }
  188. // 清理原始数据中的关联字段
  189. delete data[fieldName];
  190. }
  191. }
  192. }
  193. /**
  194. * 创建实体
  195. */
  196. async create(data: DeepPartial<T>, userId?: string | number): Promise<T> {
  197. const entityData = { ...data };
  198. this.setUserFields(entityData, userId, true);
  199. // 分离关联字段数据
  200. const relationData: any = {};
  201. if (this.relationFields) {
  202. for (const fieldName of Object.keys(this.relationFields)) {
  203. if (fieldName in entityData) {
  204. relationData[fieldName] = (entityData as any)[fieldName];
  205. delete (entityData as any)[fieldName];
  206. }
  207. }
  208. }
  209. const entity = this.repository.create(entityData as DeepPartial<T>);
  210. // 处理关联字段
  211. await this.handleRelationFields(relationData, entity);
  212. return this.repository.save(entity);
  213. }
  214. /**
  215. * 更新实体
  216. */
  217. async update(id: number, data: Partial<T>, userId?: string | number): Promise<T | null> {
  218. const updateData = { ...data };
  219. this.setUserFields(updateData, userId, false);
  220. // 分离关联字段数据
  221. const relationData: any = {};
  222. if (this.relationFields) {
  223. for (const fieldName of Object.keys(this.relationFields)) {
  224. if (fieldName in updateData) {
  225. relationData[fieldName] = (updateData as any)[fieldName];
  226. delete (updateData as any)[fieldName];
  227. }
  228. }
  229. }
  230. // 先更新基础字段
  231. await this.repository.update(id, updateData);
  232. // 获取完整实体并处理关联字段
  233. const entity = await this.getById(id);
  234. if (!entity) return null;
  235. // 处理关联字段
  236. await this.handleRelationFields(relationData, entity, true);
  237. return this.repository.save(entity);
  238. }
  239. /**
  240. * 删除实体
  241. */
  242. async delete(id: number): Promise<boolean> {
  243. const result = await this.repository.delete(id);
  244. return result.affected === 1;
  245. }
  246. /**
  247. * 高级查询方法
  248. */
  249. createQueryBuilder(alias: string = 'entity') {
  250. return this.repository.createQueryBuilder(alias);
  251. }
  252. }
  253. export interface UserTrackingOptions {
  254. createdByField?: string;
  255. updatedByField?: string;
  256. userIdField?: string;
  257. }
  258. export interface RelationFieldOptions {
  259. [fieldName: string]: {
  260. relationName: string;
  261. targetEntity: new () => any;
  262. joinTableName?: string;
  263. };
  264. }
  265. export type CrudOptions<
  266. T extends ObjectLiteral,
  267. CreateSchema extends z.ZodSchema = z.ZodSchema,
  268. UpdateSchema extends z.ZodSchema = z.ZodSchema,
  269. GetSchema extends z.ZodSchema = z.ZodSchema,
  270. ListSchema extends z.ZodSchema = z.ZodSchema
  271. > = {
  272. entity: new () => T;
  273. createSchema: CreateSchema;
  274. updateSchema: UpdateSchema;
  275. getSchema: GetSchema;
  276. listSchema: ListSchema;
  277. searchFields?: string[];
  278. relations?: string[];
  279. middleware?: any[];
  280. userTracking?: UserTrackingOptions;
  281. relationFields?: RelationFieldOptions;
  282. readOnly?: boolean;
  283. };