import { Connection, Repository, Entity, ObjectLiteral, ObjectType } from "typeorm"; import { DeepPartial } from "typeorm/common/DeepPartial"; export class EntityRepository<Type> { private $repository: Repository<Type>; get repository(): Repository<Type> { return this.$repository; } constructor(conn: Connection, type: ObjectType<Type> | string) { try { this.$repository = conn.getRepository<Type>(type); } catch (error) { throw error; } } //insert and update public async save<T extends DeepPartial<Type>>(object: T): Promise<T> { return await this.$repository.save(object); } //delete public async delete(object: Type): Promise<Type> { return await this.$repository.remove(object); } /** * 通过Id查找 * * @param {number} id * @returns {(Promise<Type | undefined>)} * @memberof EntityRepository */ public async queryById(id: number): Promise<Type | undefined> { return await this.$repository.findOneById(id); } /** * 通过字段查找 * @param name * @param value */ public async queryByField<K extends keyof Type>( name: K, value: Type[K] ): Promise<Type | undefined> { let conditions: DeepPartial<Type> = <any>new Object(); conditions[<any>name] = value; return await this.$repository.findOne(conditions); } public async queryMany( where?: Partial<Type> | ObjectLiteral | string, order?: { [P in keyof Type]?: "ASC" | "DESC" | 1 | -1 } ): Promise<Type[]> { return this.$repository.find({ where: where, order: order }); } public async queryOne( where: Partial<Type> | ObjectLiteral | string, order?: { [P in keyof Type]?: "ASC" | "DESC" | 1 | -1 } ): Promise<Type | undefined> { return this.$repository.findOne({ where: where, order: order }); } /** * 计数 * @param where */ public async count( where: Partial<Type> | ObjectLiteral | string ): Promise<number> { return await this.$repository.count({ where: where }); } /** * 分页查询数据 * @param offset * @param max * @param where * @param order * sample: * queryPaged( * offset, * pagesize, * { field1: value1 }, * { id: "DESC" } * ); */ public async queryPaged( offset: number, max: number, where?: Partial<Type> | ObjectLiteral | string, order?: { [P in keyof Type]?: "ASC" | "DESC" | 1 | -1 } ): Promise<Type[]> { return await this.$repository.find({ skip: offset, take: max, where: where, order: order }); } }