2
0

generic-crud.service.ts 8.6 KB

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