Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 332
m_downey Avatar asked Sep 04 '18 01:09

m_downey


2 Answers

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()}'` })

like image 122
Timshel Avatar answered Oct 12 '22 23:10

Timshel


@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();
}
like image 32
Oskari Liukku Avatar answered Oct 13 '22 00:10

Oskari Liukku