0

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:

Jaqueline
  • 465
  • 2
  • 8
  • 25
  • On Stack Overflow, it's expected that you make an attempt at solving the problem on your own before posting. If you get stuck, post the code that isn't working the way you expect along with a description. – Doug Stevenson Apr 19 '20 at 22:51
  • @DougStevenson Please check my edits. – Jaqueline Apr 19 '20 at 22:59
  • If you are new to JavaScript, Cloud Functions for Firebase is not the best way to learn it. I recommend first reading the [Firebase documentation for Web developers](https://firebase.google.com/docs/database/web/start) and/or taking the [Firebase codelab for Web developer](https://codelabs.developers.google.com/codelabs/firebase-web/). They cover many basic JavaScript, Web and Firebase interactions. You could also use the Admin SDK in a local Node.js process, which can be debugged with a local debugger. After those you'll be much better equipped to write code for Cloud Functions too. – Frank van Puffelen Apr 19 '20 at 23:06
  • 1
    All you have done in your edit is change the type of function. The body of the code is exactly the same. It looks like you haven't made an attempt at actually making it work the way you want. – Doug Stevenson Apr 19 '20 at 23:38
  • @DougStevenson I've just gone through to try something I saw in a few resources that I listed having to do with Firestore. I hope what I provided is a basis that we can build off of. I would greatly appreciate your help. – Jaqueline Apr 21 '20 at 04:15
  • @FrankvanPuffelen I've tried to combine your method on a previous post, but for Firestore and so far this is where I got (in the new edits). I'm really stuck on what to do further or what to change, and would appreciate your help on continuing my question. – Jaqueline Apr 21 '20 at 04:17
  • Great job on converting the code so far! Where in the code do you now get that error message from the compiler? – Frank van Puffelen Apr 21 '20 at 13:58
  • @FrankvanPuffelen Thank you, I appreciate it. I get that error on line const snapshots... the get() didn’t show up automatically as a suggestion as I was typing like everything else does so I’m not sure if there’s a different way of getting those documents? – Jaqueline Apr 21 '20 at 15:26
  • Ah... that's because you're using `await`. That keyword is only valid inside a function that is marked as `async`. So `.onWrite(async(change, context) => {` – Frank van Puffelen Apr 21 '20 at 16:15
  • @FrankvanPuffelen That made the error go away. Is everything else in the function as it should be? – Jaqueline Apr 22 '20 at 04:04
  • I can't say that at a glance, but you can test it to see. I'd always recommend testing just the JavaScript code somewhere else first, where it's easier to modify. The emulators might also be good for that, but I'm not very fluent with those yet myself. – Frank van Puffelen Apr 22 '20 at 04:09
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/212226/discussion-between-jaqueline-and-frank-van-puffelen). – Jaqueline Apr 22 '20 at 04:10

0 Answers0