import { EntityRepository, FindConditions, FindOneOptions, Repository } from "typeorm"; import { User } from "@server/entities"; export interface FindUserOptions extends FindOneOptions { devices: boolean; } function computeOptions( options?: Partial ): FindOneOptions { const opts: FindUserOptions = { devices: false, ...options }; const { devices, ...rest } = opts; const relations = [devices && "devices"].filter(Boolean) as string[]; return { relations, ...rest }; } @EntityRepository(User) export class UserRepository extends Repository { findAll(options?: Partial) { const opts = computeOptions(options); return super.find(opts); } findOneUser(conditions: FindConditions, options?: Partial) { const opts = computeOptions(options); return super.findOne(conditions, opts); } findById(id: number, options?: Partial) { return this.findOneUser({ id }, options); } findByUsername(username: string, options?: Partial) { return this.findOneUser({ username }, options); } // async checkAndSave(entity: User): Promise { // return this.manager.transaction(manager => { // let query = manager.createQueryBuilder(User, "user", manager.queryRunner!); // if (entity.id != null) { // query = query.where("user.id <> :id", { id: entity.id }) // } // query // return manager.save(entity); // }); // } }