When using TypeORM with PostgreSQL, generating UUIDs automatically is highly beneficial, especially when handling data rows that require unique identifiers. To implement automatically generated UUIDs in TypeORM, you can achieve this through several approaches.
Using Database Default Values
In PostgreSQL, you can utilize the uuid-ossp extension, which provides functions for generating UUIDs. First, ensure your PostgreSQL database has the uuid-ossp extension installed. You can install it by executing the following SQL command:
sqlCREATE EXTENSION IF NOT EXISTS "uuid-ossp";
Next, within your TypeORM entity, use the @Column decorator and specify the default property to invoke the uuid_generate_v4() function, which automatically generates a UUID each time a new record is created. For example:
typescriptimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn('uuid') id: string; @Column({ type: 'varchar', length: 255 }) name: string; }
In the above code, @PrimaryGeneratedColumn('uuid') instructs TypeORM to use UUID as the primary key and to generate new UUID values by default using PostgreSQL's uuid_generate_v4() function.
Using TypeORM Decorators
If you prefer not to rely on database defaults or wish to handle UUID generation at the application level, you can employ the BeforeInsert decorator in TypeORM to generate UUIDs before inserting records. This can be done using the uuid library for JavaScript; first, install this library:
bashnpm install uuid
Then, import and integrate it into your entity:
typescriptimport { Entity, PrimaryColumn, Column, BeforeInsert } from 'typeorm'; import { v4 as uuidv4 } from 'uuid'; @Entity() export class User { @PrimaryColumn() id: string; @Column({ type: 'varchar', length: 255 }) name: string; @BeforeInsert() addId() { this.id = uuidv4(); } }
In this example, the addId function is triggered before inserting a new User instance, setting the id field to a newly generated UUID.
Summary
The choice of method depends on your preference regarding the division of responsibilities between the database and application logic. Using database defaults (such as uuid-ossp) effectively leverages database capabilities, while generating UUIDs at the application level (e.g., with the uuid library and @BeforeInsert) offers greater flexibility and control. When selecting an approach, consider your application's specific requirements and the expected database interaction patterns.