From 5a82195540fb79052bdd836c3af4a0e8ecc50453 Mon Sep 17 00:00:00 2001 From: mfreund Date: Mon, 20 May 2024 17:32:35 +0200 Subject: [PATCH] Fix for updating the history document --- functions/src/history.ts | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/functions/src/history.ts b/functions/src/history.ts index f9c6eb2..f2a5fb2 100644 --- a/functions/src/history.ts +++ b/functions/src/history.ts @@ -18,14 +18,27 @@ export const pushToHistory = onCall({ maxInstances: 1 }, async (request) => { const historyDocRef = db.doc(`aggregates/history`); - historyDocRef.get(). - then(snapshot => snapshot.data() as History). - then(history => { - var newEntries = history.entries.filter(entry => entry.recipeId !== recipeId); - newEntries.unshift({"recipeId": recipeId, "timestamp": Timestamp.now()}); - return newEntries.slice(0, 10); - }). - then(newEntries => { - historyDocRef.set({entries: newEntries}); - }); + let history : History = { + entries: [] + }; + + try { + history = await historyDocRef.get().then(snapshot => snapshot.data() as History); + if (typeof(history.entries) !== 'object') { + history.entries = []; + } + } catch (e) { + console.error("Unable to convert document 'aggregates/history' to an instance of History. " + + "The following error occurred: " + e); + } + + console.log(`Old history: ${history}`); + + var newEntries = history.entries.filter(entry => entry.recipeId !== recipeId); + newEntries.unshift({"recipeId": recipeId, "timestamp": Timestamp.now()}); + history.entries = newEntries.slice(0, 10); + + console.log(`New entries: ${history}`); + + await historyDocRef.set(history); }); \ No newline at end of file