From 73def8a682e0c2a32bc5c191ed4fdfd7aee47ac0 Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Fri, 24 Nov 2023 10:29:59 +0500 Subject: [PATCH] core: prevent duplicate colors based on color code --- packages/core/src/collections/colors.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/core/src/collections/colors.ts b/packages/core/src/collections/colors.ts index d32fee675..2803fadba 100644 --- a/packages/core/src/collections/colors.ts +++ b/packages/core/src/collections/colors.ts @@ -50,6 +50,10 @@ export class Colors implements ICollection { return this.collection.get(id); } + find(colorCode: string) { + return this.all.find((eb) => eb.and([eb("colorCode", "==", colorCode)])); + } + // async merge(remoteColor: MaybeDeletedItem) { // if (!remoteColor) return; @@ -62,14 +66,22 @@ export class Colors implements ICollection { if (item.remote) throw new Error("Please use db.colors.merge to merge remote colors."); - const id = item.id || getId(item.dateCreated); - const oldColor = await this.color(id); - item.title = item.title ? Tags.sanitize(item.title) : item.title; + const oldColor = item.id + ? await this.color(item.id) + : item.colorCode + ? await this.find(item.colorCode) + : undefined; + if (!item.title && !oldColor?.title) throw new Error("Title is required."); if (!item.colorCode && !oldColor?.colorCode) throw new Error("Color code is required."); + const id = + oldColor && item.colorCode === oldColor.colorCode + ? oldColor.id + : item.id || getId(item.dateCreated); + await this.collection.upsert({ id, dateCreated: item.dateCreated || oldColor?.dateCreated || Date.now(),