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.
@PrimaryGeneratedColumn('uuid')
means that the database field type will beuuid
, which you can't insert a non-valid UUID in. I'd suggest decorating with @PrimaryColumn('char', { length: <shortId length> }) and using a@BeforeInsert
listener as you describe. This will give you a fixed-length character primary key for the shortId. – Fahy@PrimaryColumn('varchar', { length: <max-shortid-length> })
instead of the above... – Fahy@PrimaryColumn('varchar', { default: shortid.generate(), length: 14 })
thanks for your help! I'd vote up your comments but it won't let me :/ – Tipcatdefault
option, are you passing the function itself (iedefault: shortid.generate
) or calling it and defaulting to its return value (default: shortid.generate()
)? Unless I'm mistaken you'll need the former - otherwise TypeORM will have a single default value each time your app starts and will allow inserting one record but then error with a duplicate key violation for subsequent records. – Fahycolumn "gz68lzqnmn" does not exist
(the id changes each time) error. The only way around this I found was to keepdefault: shortid.generate()
but then in the BeforeInsert hook I addedthis.id = shortid.generate()
. Very hacky and sad :( but it works. If you want to look further into this you could pull this repo andyarn start
to reproduce. No pressure though. Thanks again! github.com/podverse/podverse-api/tree/primaryDefaultBug – Tipcatshortid.generate()
and quoting the value should be all that is needed - e.g.default: () => `'${shortid.generate()}'`
(note the single quotes around the ID). – Fahy