'How do you set a custom default unique id string for the @PrimaryGeneratedColumn in a TypeORM Entity?
I have a use case that calls for a custom string primary key in my tables. (I don't want to use the default 'uuid' provided by GraphQL, but instead want to use the shortid library to generate a custom unique id instead.)
I'm a TypeORM beginner, and I'm not finding anything about setting a custom default primary key in the docs. Is it possible to achieve what I want in the TypeORM PrimaryGeneratedColumn, or do I have to accomplish what I want by other means?
UPDATE: I learned I can use the @BeforeInsert listener to modify entities before saving them, but TypeORM still doesn't let me override the PrimaryGeneratedColumn('uuid') and use a shortId string because the shortId string is not a valid uuid.
Solution 1:[1]
@Timshel's answer does not work when using SQLite, because default values must be constant. It gives the following error:
UnhandledPromiseRejectionWarning: QueryFailedError: SQLITE_ERROR: default value of column [id] is not constant
Instead, you can use @BeforeInsert to achieve the desired result, like so:
@Field(() => ID)
@PrimaryColumn("varchar", {
length: 20
})
id: string;
@BeforeInsert()
setId() {
this.id = shortid.generate();
}
Solution 2:[2]
Great thanks to the answers from Timshel and Oskari Liukku!
There is a complementary to their answer.
Recently, shortid was depricated, and on their main page they recommend to use nanoid.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oskari Liukku |
| Solution 2 |
