Search code examples
javascriptentitytypeorm

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

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