By harnessing the power of NestJS and TypeORM in the year 2024, you have the capability to utilize the upsert function to effectively manage all potential edge cases that may arise.
Imagine a scenario where you are working with an entity named Thing, which consists of attributes like name and color.
@Entity("thing")
@Unique(["name", "color"])
export class Thing {
@PrimaryGeneratedColumn()
id: string;
@Column()
name: string;
@Column()
color: string;
// more properties can be added here
}
The challenge occurs when the id
of the Thing entity is interconnected with various tables in your database, resulting in potential foreign key constraint violations.
You can seamlessly address this issue by implementing the upsert feature along with specific configuration options.
Here's an example implementation demonstrating how you can use upsert with detailed settings:
await repository.upsert(
[
{ name: "a red thing", color: "red" },
{ name: "a blue thing", color: "blue" },
],
{
conflictPaths: ["name", "color"],
skipUpdateIfNoValuesChanged: true,
upsertType: "on-conflict-do-update",
}
);
If you encounter any challenges despite this approach, you can resort to a fail-safe method utilizing the following code snippet:
const repository = dataSource.getRepository(Thing);
await repository
.createQueryBuilder()
.insert()
.into(Thing)
.values([
{ name: "a red thing", color: "red" },
{ name: "a blue thing", color: "blue" },
])
.orUpdate(["name", "color"])
.orIgnore()
.execute();