I have been trying to find a way in which the documents from a collection in firestore can get deleted after a certain amount of time in my case 24h, for doing this I realized that I have to use firebase cloud functions so after investigating I found this post which does the work that I need to add in my project except that I am using typescript instead of javascript which is being used in that question and I cant change it to javascript because I am already using typescipt for sending notifications to users. How can I change the following code to typescript?
//index.ts
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp()
const db = admin.firestore();
export const deleteOldItems = functions.database
.ref('stories/{storyId}')
.onWrite((change, context) => {
var ref = change.after.ref.parent;
var now = Date.now();
var cutoff = now - 24 * 60 * 60 * 1000;
var oldItemsQuery = ref.orderByChild('created').endAt(cutoff);
return oldItemsQuery.once('value', function(snapshot) {
// create a map with all children that need to be removed
var updates = {};
snapshot.forEach(function(child) {
updates[child.key] = null
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
});
here is an image of the data that needs to be erased after 24h, created field is the date when the document was created and deleted id the date where the doc should be deleted.
EDIT: I turns out the problem is not because of using typescript but because I am using firestore instead of firebase real time database so I created this code which is supposed to make things work but it doesnt. How can I fix this?
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp()
const db = admin.firestore();
export const deleteOldItems = functions.firestore
.document('stories/{storyId}')
.onWrite(async (change, context) => {
const getData = await db.collection('stories').where('deleted', '>', Date.now()).get().then(
(snapshot) => snapshot.forEach((doc) =>
doc.ref.delete()
)
);
return getData;
});