From 399ec9010873be91e08d2130a71ebfc87eb53589 Mon Sep 17 00:00:00 2001 From: Safwan Parkar Date: Thu, 10 Aug 2023 09:47:53 +0400 Subject: [PATCH] use deep clone instead of reference copy - Original code creates a reference copy of `$doc` into `$work` which means that editing values of `$work` changes the values in `$doc`. - Fix this behaviour by creating a deep clone of `$doc` into `$work`, so underlying values aren't cross-referenced. --- src/lib/helpers/object.ts | 11 +++++++ .../document-[document]/data/+page.svelte | 33 ++++++++++--------- 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/src/lib/helpers/object.ts b/src/lib/helpers/object.ts index ca6a370a3..6f7a24723 100644 --- a/src/lib/helpers/object.ts +++ b/src/lib/helpers/object.ts @@ -36,3 +36,14 @@ export function deepEqual(obj1: T, obj2: T): boolean { return true; } + +/** + * Creates a deep clone of the given object. This function uses the JSON methods for cloning, + * so it may not be suitable for objects with functions, symbols, or other non-JSON-safe data. + * + * @param obj the object to be cloned + * @returns a deep clone of the provided object + */ +export function deepClone(obj: T): T { + return JSON.parse(JSON.stringify(obj)); +} diff --git a/src/routes/console/project-[project]/databases/database-[database]/collection-[collection]/document-[document]/data/+page.svelte b/src/routes/console/project-[project]/databases/database-[database]/collection-[collection]/document-[document]/data/+page.svelte index 58a16758f..c435b460b 100644 --- a/src/routes/console/project-[project]/databases/database-[database]/collection-[collection]/document-[document]/data/+page.svelte +++ b/src/routes/console/project-[project]/databases/database-[database]/collection-[collection]/document-[document]/data/+page.svelte @@ -15,6 +15,7 @@ import AttributeItem from '../attributeItem.svelte'; import { symmetricDifference } from '$lib/helpers/array'; import { isRelationship, isRelationshipToMany } from '../attributes/store'; + import { deepClone } from '$lib/helpers/object'; const databaseId = $page.params.database; const collectionId = $page.params.collection; @@ -22,21 +23,23 @@ const editing = true; const work = writable( - Object.keys($doc) - .filter((key) => { - return ![ - '$id', - '$collection', - '$collectionId', - '$databaseId', - '$createdAt', - '$updatedAt' - ].includes(key); - }) - .reduce((obj, key) => { - obj[key] = $doc[key]; - return obj; - }, {}) as Models.Document + deepClone( + Object.keys($doc) + .filter((key) => { + return ![ + '$id', + '$collection', + '$collectionId', + '$databaseId', + '$createdAt', + '$updatedAt' + ].includes(key); + }) + .reduce((obj, key) => { + obj[key] = $doc[key]; + return obj; + }, {}) as Models.Document + ) ); async function updateData() {