How to auto generated UUID in PostgreSQL in TypeORM
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 ValuesIn PostgreSQL, you can utilize the extension, which provides functions for generating UUIDs. First, ensure your PostgreSQL database has the extension installed. You can install it by executing the following SQL command:Next, within your TypeORM entity, use the decorator and specify the property to invoke the function, which automatically generates a UUID each time a new record is created. For example:In the above code, instructs TypeORM to use UUID as the primary key and to generate new UUID values by default using PostgreSQL's function.Using TypeORM DecoratorsIf you prefer not to rely on database defaults or wish to handle UUID generation at the application level, you can employ the decorator in TypeORM to generate UUIDs before inserting records. This can be done using the library for JavaScript; first, install this library:Then, import and integrate it into your entity:In this example, the function is triggered before inserting a new instance, setting the field to a newly generated UUID.SummaryThe choice of method depends on your preference regarding the division of responsibilities between the database and application logic. Using database defaults (such as ) effectively leverages database capabilities, while generating UUIDs at the application level (e.g., with the library and ) offers greater flexibility and control. When selecting an approach, consider your application's specific requirements and the expected database interaction patterns.