Search code examples
node.jstypescriptvalidationnestjstypeorm

Force TypeORM to Check all columns using the decorators - NestJS


Is there a way to force the uniqueness validator in the TypeORM entity to check all the columns and then return a message for all the errors it finds?

for example, this schema:

import {
  BaseEntity,
  Column,
  Entity,
  PrimaryGeneratedColumn,
  Unique,
} from 'typeorm';

@Entity()
@Unique('UQ_USERNAME', ['username'])
@Unique('UQ_EMAIL', ['email'])
export class UserModel extends BaseEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;
  @Column()
  username: string;
  @Column()
  pwd: string;
  @Column()
  email: string;
}

if the email and username are not unique, it will check the username first, then return an error for the username only. It will not continue to check the email.

I need to know all the errors in the columns to handle them all in the frontend, not every error separately.

Note: I don't want to check every column of them with the code using (.find) method if there is a way to get this result by typeorm decorators directly it will be better than do a multiple request from databases for the same functionality of the (@Unique) decorator


Solution

  • Most databases will respond with the first constraint failed, not all of the issues with a data modification query, as a way to keep load lighter on the server (if it's gonna fail anyways, why keep going?). So the only way to know if you'll violate multiple constrains (like unique username and unique email) is to query for both and then parse the results yourself.

    In the comments, you asked if it's more cost efficient to use a query to search for this or to keep it to the UNIQUE constraint. If you go with the query approach and don't have the UNIQUE constraint on the table, you're opening yourself up to eventually allow for duplicates, either from the possibility of multiple requests at the same time that cause the searches to come back with no results, but allow for the inserts to happen, or direct modification of the database.

    Keep with the use of UNIQUE in the table definition, and handle how the database returns the errors. It will almost undoubtedly be a better approach.