Search code examples
javascriptdatabasetypescriptuuidtypeorm

Is it possible to add table prefixes for uuids in TypeORM?


I have a lot of UUIDs in various places throughout my database, and the readability would be significantly improved if they contained a prefix to denote the type of entity they are for, such as user-09a9c8fb-dcb6-5d18-9697-e1d10c552c14 or comment-c80c8502-4cd9-483f-9b81-705a22dba3a8. Is there any way to accomplish this purely with TypeORM syntax?

Here is an example of my current user model:

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
} from 'typeorm';

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

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

  @Column()
  email: string;

  @CreateDateColumn()
  createdAt: Date;
}

Solution

  • const generatePrefixedUUID = (prefix: string = ""): string => {
      return prefix + uuidv4().slice(prefix.length);
    };
    
    @PrimaryColumn({
      name: "id",
      unique: true,
    })
    id: string = generatePrefixedUUID("OR#");
    

    This should be the simple solution.
    Note: Use PrimaryColumn instead of PrimaryGeneratedColumn