Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I query an array in TypeORM

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();
like image 407
jofrly Avatar asked Oct 20 '19 16:10

jofrly


People also ask

What is Query Builder in TypeORM?

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.

Is TypeORM still maintained?

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.

Is TypeORM a database?

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.


1 Answers

As Mykhalio mentioned , you can use the PostgreSQL array functions to do the trick.

Adding few more pointers.

  1. If you want to check users with both USER_ADMIN and SUPER_ADMIN permissions.
.where('user.permissions @> :permissions', { permissions:['USER_ADMIN', 'SUPER_ADMIN']})
  1. If you want to check users with either USER_ADMIN or SUPER_ADMIN permissions.
.where('user.permissions && :permissions', { permissions: ['USER_ADMIN', 'SUPER_ADMIN']})
like image 50
Shijo Joseph Avatar answered Sep 27 '22 23:09

Shijo Joseph