davmik2601 / typeorm-scoped

MIT License
9 stars 1 forks source link

Disabling default scope for relations #2

Open 3buson opened 3 months ago

3buson commented 3 months ago

Good job on implementing a library that enables scopes for TypeORM! I've been developing an app using the library and it works well. I have one issue with relations though. Let's say I have 2 tables, users, and sessions. As you can imagine the user can have multiple sessions.

I have a default scope on the user to not show users without the rating throughout the app. When I'm loading sessions with eager loading of the user the ones that are attached to users without rating are not fetched. I'm using a standard approach with calling findOne() on the session repository (this.sessionRepository.findOne({where: { id: sessionId }});). Is there a possibility to change this behavior?

Code samples

User entity:

@DefaultScopes<User>({
  registered: (qb, alias) => qb.andWhere(`${alias}.rating IS NOT NULL`),
})
@Entity('users')
export class User extends BaseEntity {
  @Column({ default: false })
  isPayingUser?: boolean;

  @Column({ default: false })
  isAdmin!: boolean;

  @Column({ unique: true })
  email!: string;

  @Index()
  @Column({ unique: true })
  username!: string;

  @Index()
  @Column()
  firstName!: string;

  @Index()
  @Column()
  lastName!: string;

  @Index()
  @Column({ nullable: true })
  rating?: number;

  @OneToMany(() => Session, (session) => session.user)
  sessions!: Session[];
}

Session entity:

@Entity('sessions')
export class Session extends BaseEntity {
  @Column({ nullable: true })
  refreshToken?: string;

  @Column()
  userId!: string;

  @ManyToOne(() => User, (user) => user.sessions, { onDelete: 'CASCADE', eager: true })
  user!: User;
}

Base entity:

export class BaseEntity extends ScopeEntity {
  @PrimaryColumn({ length: 12 })
  id!: EntityId;

  @Index()
  @CreateDateColumn()
  createdAt!: Date;

  @Index()
  @UpdateDateColumn()
  updatedAt!: Date;

  @BeforeInsert()
  generateEntityId() {
    this.id = generateId();
  }
}
davmik2601 commented 2 months ago

@3buson , Sorry for responding so late, i am not active in this months. Yes need to check this problem for eager relations, I didnt check for eager relations. But i will work on issues after this month. So now this issue will be open.

3buson commented 2 months ago

@3buson , Sorry for responding so late, i am not active in this months. Yes need to check this problem for eager relations, I didnt check for eager relations. But i will work on issues after this month. So now this issue will be open.

Thanks for your response. I can also try to take some time to help with fixing. Do you have a specific process in place for submitting pull requests? Do you have any tests for the library? There don't seem to be any in the GitHub repository.