Last active
November 11, 2023 21:17
-
-
Save antoine-pous/9a7ebbe3f6339ceb63d3f6fb6e90308a to your computer and use it in GitHub Desktop.
TypeORM upsert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const upsert = async <Entity>(entity: ObjectType<Entity>, data: Entity, m: EntityManager, rawPKName: string = 'id'): Promise<InsertResult> => { | |
const keys: string[] = Object.keys(data) | |
if(keys.length < 1) { | |
throw Error(`Cannot upsert empty ${entity?.name || entity.constructor.name}`) | |
} | |
const updateStr: string = keys.map(key => `"${key}" = EXCLUDED."${key}"`).join(',') | |
return m.getRepository(entity) | |
.createQueryBuilder() | |
.insert() | |
.values(data) | |
.onConflict(`("${rawPKName}") DO UPDATE SET ${updateStr}`) | |
.execute() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Strong typed upsert function for TypeORM
This function works as intended for my own usage, I'm sharing it without restriction. Feel free to enhance it to make it even more generic but still typed.
Arguments
id
, but you can specify any PK name like it is in your DBUsage