From 74f60744b0b95326e26233f6226ab61704c3c70c Mon Sep 17 00:00:00 2001 From: Felix Angelov Date: Fri, 6 May 2022 18:36:53 -0500 Subject: [PATCH] feat: fix delete functionality --- functions/index.js | 48 +++++++++++++++++++++------------------------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/functions/index.js b/functions/index.js index 8e9460c5..1f676c41 100644 --- a/functions/index.js +++ b/functions/index.js @@ -1,32 +1,28 @@ const functions = require("firebase-functions"); -const admin = require('firebase-admin'); +const admin = require("firebase-admin"); admin.initializeApp(); const db = admin.firestore(); exports.timedLeaderboardCleanup = functions.firestore - .document('leaderboard/{leaderboardEntry}') - .onCreate((snap, context) => { - functions.logger.info('Document created, getting all leaderboard documents') - var allLeaderBoardEntries = db.collection('leaderboard').orderBy('score','desc').get().then(function(snapshot) { - functions.logger.info('Leaderboard contains ' + snapshot.docs.length + ' entries'); - if(snapshot.docs.length > 10) { - for(var i = 10; i < snapshot.docs.length; i++) { - functions.logger.info('Deleting entry number ' + (i + 1) + ' in the leaderboard'); - snapshot.docs[i].ref.delete() - .then(function() { - functions.logger.info('Delete successful'); - return true; - }) - .catch(function(error) { - functions.logger.error('Error in Deleting record'); - return false; - }); - } - } - else { - functions.logger.info('Leaderboard is less then 10 entries. No action taken.'); - return true; - } - }); - }); \ No newline at end of file + .document("leaderboard/{leaderboardEntry}") + .onCreate(async (_, __) => { + functions.logger.info( + "Document created, getting all leaderboard documents" + ); + const snapshot = await db + .collection("leaderboard") + .orderBy("score", "desc") + .offset(10) + .get(); + + functions.logger.info( + `Preparing to delete ${snapshot.docs.length} documents.` + ); + try { + await Promise.all(snapshot.docs.map((doc) => doc.ref.delete())); + functions.logger.info("Success"); + } catch (error) { + functions.logger.error(`Failed to delete documents ${error}`); + } + });