Reputation: 155
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.
Upvotes: 12
Views: 26734
Reputation: 113
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
.
Upvotes: 2
Reputation: 126
@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();
}
Upvotes: 7
Reputation: 1783
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()}'` })
Upvotes: 14