2
0

generic-crud.service.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. const alias = parts.slice(0, -1).join('_'); // 使用下划线连接关系路径作为别名
  59. const fieldName = parts[parts.length - 1];
  60. searchConditions.push(`${alias}.${fieldName} LIKE :keyword`);
  61. } else {
  62. // 普通字段搜索
  63. searchConditions.push(`entity.${field} LIKE :keyword`);
  64. }
  65. });
  66. if (searchConditions.length > 0) {
  67. query.andWhere(`(${searchConditions.join(' OR ')})`, searchParams);
  68. }
  69. }
  70. // 条件查询
  71. if (where) {
  72. Object.entries(where).forEach(([key, value]) => {
  73. if (value !== undefined && value !== null) {
  74. query.andWhere(`entity.${key} = :${key}`, { [key]: value });
  75. }
  76. });
  77. }
  78. // 扩展筛选条件
  79. if (filters) {
  80. Object.entries(filters).forEach(([key, value]) => {
  81. if (value !== undefined && value !== null && value !== '') {
  82. const fieldName = key.startsWith('_') ? key.substring(1) : key;
  83. // 检查是否为关联字段(包含点号)
  84. let tableAlias: string = 'entity';
  85. let actualFieldName: string = fieldName;
  86. if (fieldName.includes('.')) {
  87. const parts = fieldName.split('.');
  88. tableAlias = parts.slice(0, -1).join('_') || 'entity'; // 使用下划线连接关系路径作为别名
  89. actualFieldName = parts[parts.length - 1] || fieldName;
  90. }
  91. // 支持不同类型的筛选
  92. if (Array.isArray(value)) {
  93. // 数组类型:IN查询
  94. if (value.length > 0) {
  95. query.andWhere(`${tableAlias}.${actualFieldName} IN (:...${key})`, { [key]: value });
  96. }
  97. } else if (typeof value === 'string' && value.includes('%')) {
  98. // 模糊匹配
  99. query.andWhere(`${tableAlias}.${actualFieldName} LIKE :${key}`, { [key]: value });
  100. } else if (typeof value === 'object' && value !== null) {
  101. // 范围查询
  102. if ('gte' in value) {
  103. query.andWhere(`${tableAlias}.${actualFieldName} >= :${key}_gte`, { [`${key}_gte`]: value.gte });
  104. }
  105. if ('gt' in value) {
  106. query.andWhere(`${tableAlias}.${actualFieldName} > :${key}_gt`, { [`${key}_gt`]: value.gt });
  107. }
  108. if ('lte' in value) {
  109. query.andWhere(`${tableAlias}.${actualFieldName} <= :${key}_lte`, { [`${key}_lte`]: value.lte });
  110. }
  111. if ('lt' in value) {
  112. query.andWhere(`${tableAlias}.${actualFieldName} < :${key}_lt`, { [`${key}_lt`]: value.lt });
  113. }
  114. if ('between' in value && Array.isArray(value.between) && value.between.length === 2) {
  115. query.andWhere(`${tableAlias}.${actualFieldName} BETWEEN :${key}_start AND :${key}_end`, {
  116. [`${key}_start`]: value.between[0],
  117. [`${key}_end`]: value.between[1]
  118. });
  119. }
  120. } else {
  121. // 精确匹配
  122. query.andWhere(`${tableAlias}.${actualFieldName} = :${key}`, { [key]: value });
  123. }
  124. }
  125. });
  126. }
  127. // 排序
  128. Object.entries(order).forEach(([key, direction]) => {
  129. query.orderBy(`entity.${key}`, direction);
  130. });
  131. const finalQuery = query.skip(skip).take(pageSize);
  132. // console.log(finalQuery.getSql())
  133. return finalQuery.getManyAndCount();
  134. }
  135. /**
  136. * 根据ID获取单个实体
  137. */
  138. async getById(id: number, relations: string[] = []): Promise<T | null> {
  139. return this.repository.findOne({
  140. where: { id } as any,
  141. relations
  142. });
  143. }
  144. /**
  145. * 设置用户跟踪字段
  146. */
  147. private setUserFields(data: any, userId?: string | number, isCreate: boolean = true): void {
  148. if (!this.userTrackingOptions || !userId) {
  149. return;
  150. }
  151. const {
  152. createdByField = 'createdBy',
  153. updatedByField = 'updatedBy',
  154. userIdField = 'userId'
  155. } = this.userTrackingOptions;
  156. // 设置创建人
  157. if (isCreate && createdByField) {
  158. data[createdByField] = userId;
  159. }
  160. // 设置更新人
  161. if (updatedByField) {
  162. data[updatedByField] = userId;
  163. }
  164. // 设置关联的用户ID(如userId字段)
  165. if (isCreate && userIdField) {
  166. data[userIdField] = userId;
  167. }
  168. }
  169. /**
  170. * 创建实体
  171. */
  172. /**
  173. * 处理关联字段
  174. */
  175. private async handleRelationFields(data: any, entity: T, _isUpdate: boolean = false): Promise<void> {
  176. if (!this.relationFields) return;
  177. for (const [fieldName, config] of Object.entries(this.relationFields)) {
  178. if (data[fieldName] !== undefined) {
  179. const ids = data[fieldName];
  180. const relationRepository = this.dataSource.getRepository(config.targetEntity);
  181. if (ids && Array.isArray(ids) && ids.length > 0) {
  182. const relatedEntities = await relationRepository.findBy({ id: In(ids) });
  183. (entity as any)[config.relationName] = relatedEntities;
  184. } else {
  185. (entity as any)[config.relationName] = [];
  186. }
  187. // 清理原始数据中的关联字段
  188. delete data[fieldName];
  189. }
  190. }
  191. }
  192. /**
  193. * 创建实体
  194. */
  195. async create(data: DeepPartial<T>, userId?: string | number): Promise<T> {
  196. const entityData = { ...data };
  197. this.setUserFields(entityData, userId, true);
  198. // 分离关联字段数据
  199. const relationData: any = {};
  200. if (this.relationFields) {
  201. for (const fieldName of Object.keys(this.relationFields)) {
  202. if (fieldName in entityData) {
  203. relationData[fieldName] = (entityData as any)[fieldName];
  204. delete (entityData as any)[fieldName];
  205. }
  206. }
  207. }
  208. const entity = this.repository.create(entityData as DeepPartial<T>);
  209. // 处理关联字段
  210. await this.handleRelationFields(relationData, entity);
  211. return this.repository.save(entity);
  212. }
  213. /**
  214. * 更新实体
  215. */
  216. async update(id: number, data: Partial<T>, userId?: string | number): Promise<T | null> {
  217. const updateData = { ...data };
  218. this.setUserFields(updateData, userId, false);
  219. // 分离关联字段数据
  220. const relationData: any = {};
  221. if (this.relationFields) {
  222. for (const fieldName of Object.keys(this.relationFields)) {
  223. if (fieldName in updateData) {
  224. relationData[fieldName] = (updateData as any)[fieldName];
  225. delete (updateData as any)[fieldName];
  226. }
  227. }
  228. }
  229. // 先更新基础字段
  230. await this.repository.update(id, updateData);
  231. // 获取完整实体并处理关联字段
  232. const entity = await this.getById(id);
  233. if (!entity) return null;
  234. // 处理关联字段
  235. await this.handleRelationFields(relationData, entity, true);
  236. return this.repository.save(entity);
  237. }
  238. /**
  239. * 删除实体
  240. */
  241. async delete(id: number): Promise<boolean> {
  242. const result = await this.repository.delete(id);
  243. return result.affected === 1;
  244. }
  245. /**
  246. * 高级查询方法
  247. */
  248. createQueryBuilder(alias: string = 'entity') {
  249. return this.repository.createQueryBuilder(alias);
  250. }
  251. }
  252. export interface UserTrackingOptions {
  253. createdByField?: string;
  254. updatedByField?: string;
  255. userIdField?: string;
  256. }
  257. export interface RelationFieldOptions {
  258. [fieldName: string]: {
  259. relationName: string;
  260. targetEntity: new () => any;
  261. joinTableName?: string;
  262. };
  263. }
  264. export type CrudOptions<
  265. T extends ObjectLiteral,
  266. CreateSchema extends z.ZodSchema = z.ZodSchema,
  267. UpdateSchema extends z.ZodSchema = z.ZodSchema,
  268. GetSchema extends z.ZodSchema = z.ZodSchema,
  269. ListSchema extends z.ZodSchema = z.ZodSchema
  270. > = {
  271. entity: new () => T;
  272. createSchema: CreateSchema;
  273. updateSchema: UpdateSchema;
  274. getSchema: GetSchema;
  275. listSchema: ListSchema;
  276. searchFields?: string[];
  277. relations?: string[];
  278. middleware?: any[];
  279. userTracking?: UserTrackingOptions;
  280. relationFields?: RelationFieldOptions;
  281. readOnly?: boolean;
  282. };