0

I'm using Firebase Functions I'm trying to delete all the documents that are past 20 min

I have been looking around for an answer but I got too confused I have seen a lot of answers pointing out a lot of options like Using Pub/Sub to trigger a Cloud Function, and cloud task and other different ways got me confused here is the code that I deployed but didn't work

import * as functions from "firebase-functions";
import * as admin from 'firebase-admin';

admin.initializeApp()

export const deleteDocument = functions.firestore
.document('Orders/{Orders}')
.onCreate((snapshot, context) => {
    const data = snapshot.data();
    if (data){
        const date = data.date;
        const date2 = Date.now();
        let diffMs = (date - date2); // milliseconds
        let diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
        console.log(diffMins);
        if (diffMins > 20) {
            snapshot.ref.delete();
        }
    }

});

where did i went wrong in this code how to test this function before deploying it

I have this error when debugging in VS Code I don't know if it's related

{"severity":"WARNING","message":"Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail"}

Doug Stevenson
  • 268,359
  • 30
  • 341
  • 380
Swift
  • 27
  • 1
  • 7
  • 1
    You mention that "[you] have seen a lot of answers pointing out a lot of options like ... cloud task". it is indeed one of the recommended way, as explained in this [article](https://medium.com/firebase-developers/how-to-schedule-a-cloud-function-to-run-in-the-future-in-order-to-build-a-firestore-document-ttl-754f9bf3214a). Your code cannot work since it is executed when the document is created and not 20 minutes after the doc creation. – Renaud Tarnec Jun 04 '22 at 13:52
  • You're going to have to use one of those confusing solutions. There is really no easy way to do what you want using only Cloud Functions, without also involving other Google Cloud products to help with timing an asynchronous function to delete the document. – Doug Stevenson Jun 04 '22 at 14:43

0 Answers0