TypeORM ManyToMany relationship efficient query

765 Views Asked by At
import { Entity, Column, BaseEntity, ManyToMany, JoinColumn, PrimaryColumn } from 'typeorm';

@Entity()
export class Permission extends BaseEntity {
    @PrimaryColumn()
    code: string;
}

@Entity()
export class Role extends BaseEntity {
    @PrimaryColumn()
    code: string;

    @ManyToMany(() => Permission, { cascade: false })
    @JoinColumn()
    permission: Permission[];
}

@Entity('users')
export class User extends BaseEntity {
    @PrimaryGeneratedColumn('uuid')
    id: string;

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

    @ManyToMany(() => Role)
    @JoinColumn()
    roles: Role[];

    @ManyToMany(() => Permission)
    @JoinColumn()
    permissions: Permission[];
}

hasPermission(user: User, code: string): Boolean => {
    // ...
}

I want to check efficiently if user has a permission or not. i.e. John is a user with role ['inventoryManager'] and permissions ['listing:delete']. And role inventoryManager has permissions ['listing:read', 'listing:update']. So, John.hasPermission('listing:update') and John.hasPermission('listing:delete') both will return true while John.hasPermission('listing:create') should return false.

While I can select all and then loop over will be a solution but I that think as inefficient and over selecting.

1

There are 1 best solutions below

0
Jim On

Have you considered using the QueryBuilder? https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#getting-the-generated-query

You could then see the query output and try different join and filtering strategies and compare their efficiency.