From 4ca8e3370e079592b8cd8506c735b5b96a2ab805 Mon Sep 17 00:00:00 2001 From: Ivan Shmidt Date: Mon, 18 May 2020 13:10:10 +0200 Subject: [PATCH] fix: moved into transaction for atomicity --- .../catalog-backend/src/database/Database.ts | 34 +++++++++++++------ 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/plugins/catalog-backend/src/database/Database.ts b/plugins/catalog-backend/src/database/Database.ts index fba8728fcd..9b37980c04 100644 --- a/plugins/catalog-backend/src/database/Database.ts +++ b/plugins/catalog-backend/src/database/Database.ts @@ -60,19 +60,31 @@ export class Database { } async addLocation(location: AddDatabaseLocation): Promise { - const existingLocation = await this.locationByTarget(location.target); - if (existingLocation) { - return existingLocation; - } + return await this.database.transaction(async tx => { + const existingLocation = await tx('locations') + .where({ + target: location.target, + }) + .select(); - const id = uuidv4(); - const { type, target } = location; - await this.database('locations').insert({ - id, - type, - target, + if (existingLocation?.[0]) { + return existingLocation[0]; + } + + const id = uuidv4(); + const { type, target } = location; + await tx('locations').insert({ + id, + type, + target, + }); + + return ( + await tx('locations') + .where({ id }) + .select() + )?.[0]; }); - return await this.location(id); } async removeLocation(id: string): Promise {