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.
The @PrimaryGeneratedColumn('uuid')
decorator maps the column to a uuid
database field type if the database supports it, which means the column values must be a valid UUIDs.
For your scenario I suggest decorating with:
typescript
@PrimaryColumn('varchar', { length: <max shortId length>, default: () => `'${shortid.generate()}'` })
@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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With