I want to create user permissions management. I use TypeORM with PostgreSQL. This is the column definition for the permissions within the user entity:
@Column({
type: 'text',
array: true
})
permissions: UserPermission[] = [];
This is the UserPermission
enum:
export enum UserPermission {
APP_USER = 'APP_USER',
USER_ADMIN = 'USER_ADMIN',
SUPERADMIN = 'SUPERADMIN'
}
I want to find one user who has the 'SUPERADMIN'
permission but I cannot find the right spot in the documentation / github issues which explains how to do this. I already spent over an hour on this and I suppose this is a simple task.
Is there something like "Includes" to check if the permissions array includes a specific element and/or includes multiple elements?
const user = await this.userRepository.findOne({
where: {
permissions: Includes('SUPERADMIN')
}
});
I would be very thankful if someone could point me to the correct documentation page :)
Edit:
The following works for me but I think it is not optimal yet:
@Column('simple-json')
permissions: string[];
let user = await this.userRepository.createQueryBuilder('user')
.where('user.permissions like :permissions', { permissions: `%"${UserPermission.SUPERADMIN}"%` })
.getOne();
Query builder is used build complex SQL queries in an easy way. It is initialized from Connection method and QueryRunner objects. We can create QueryBuilder in three ways.
TypeORM is poorly maintained (the lead author had a breakdown and appears to be inactive, and failed to delegate ownership to others), and is riddled with bad abstractions, poor design choices and an enormous pile of game-breaking bugs that make the TypeScript types unsafe and it's usage clunky and dangerous.
TypeORM supports multiple databases like MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana and WebSQL. TypeORM is an easy-to-use ORM to scaffold new apps that connect to databases. TypeORM functionality is RDBMS-specific concepts. We can quickly create new projects and micro-services.
As Mykhalio mentioned , you can use the PostgreSQL array functions to do the trick.
Adding few more pointers.
.where('user.permissions @> :permissions', { permissions:['USER_ADMIN', 'SUPER_ADMIN']})
.where('user.permissions && :permissions', { permissions: ['USER_ADMIN', 'SUPER_ADMIN']})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With