I've already done this on the Firebase Realtime Database and it's worked perfectly before, but I decided to switch to Firestore and am trying to have the same functionality with the cloud functions.
My goal: Have a cloud function that deletes messages after 24 hours from Firestore
I've tried to use the same function that I had and convert it over to Firestore, but the syntax isn't correct and I'm not very familiar with Javascript.
This is the code for the cloud function which worked form my RTDB:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 24 * 60 * 60 * 1000; // 24 Hours in seconds.
exports.deleteOldMessages = functions.database.ref('/Message/{chatRoomID}/{messageId}').onWrite(function(change) {
var ref = change.after.ref.parent;
var now = Date.now()
var cutoff = (now - CUT_OFF_TIME) / 1000;
var oldItemsQuery = ref.orderByChild('seconds').endAt(cutoff);
return oldItemsQuery.once('value').then(function(snapshot) {
var updates = {};
snapshot.forEach(function(child) {
updates[child.key] = null;
console.log(cutoff)
});
return ref.update(updates);
});
});
Path: My path in the Firestore is different from the RTDB. Collection('Message').Document('userId' (the actual userId of that user)).Collection('chatRoomId' (the actual chatRoomId of that chat)).Document('messageId') and then one of the fields is Seconds: 1587334120
I would greatly appreciate it if someone could help me try to convert/have the same functionality as my previous Cloud Function, but works for Firestore and incorporates the new path. All help is greatly appreciated
Edit: This is what I was able to try and figure out on my own. I understand that I have to query the collection based off of the seconds, and from there see if it's past 24 hours, then delete the document, but I'm unsure on the syntax on how to do it. In the compiler I get the error "Unexpected token query aslant [28, 25]"
exports.deleteOldFirestoreMessages = functions.firestore.document('Message/{userId}/{chatRoomId}/{messageId}').onWrite((change, context) => {
var now = Date().now
var cutoff = (now - CUT_OFF_TIME) / 1000;
const query = admin.firestore().collection('Message/{userId}/{chatRoomId}').where('seconds', '>=', cutoff)
const snapshots = await query.get();
const batch = firestore.batch();
snapshots.forEach(v => batch.delete(v.ref));
await batch.commit();
});
These are the resources I've tried looking through: