Home > Software engineering >  How to use firebase cloud functions' firestore.onWrite() in netlify lamda
How to use firebase cloud functions' firestore.onWrite() in netlify lamda

Time:09-14

I want to aggregate firestore data but I want to go with netlify lambda for the serverless functions. I want to do something like

onst functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.aggregateComments = functions.firestore
    .document('posts/{postId}/comments/{commentId}')
    .onWrite(event => {

    const commentId = event.params.commentId; 
    const postId = event.params.postId;
    
    // ref to the parent document
    const docRef = admin.firestore().collection('posts').doc(postId)
    
    // get all comments and aggregate
    return docRef.collection('comments').orderBy('createdAt', 'desc')
         .get()
         .then(querySnapshot => {

            // get the total comment count
            const commentCount = querySnapshot.size

            const recentComments = []

            // add data from the 5 most recent comments to the array
            querySnapshot.forEach(doc => {
                recentComments.push( doc.data() )
            });

            recentComments.splice(5)

            // record last comment timestamp
            const lastActivity = recentComments[0].createdAt

            // data to update on the document
            const data = { commentCount, recentComments, lastActivity }
            
            // run update
            return docRef.update(data)
         })
         .catch(err => console.log(err) )
});

but I can't get it to work on netlify lambda. Is there anyway I can use this function in netlify lambda?

CodePudding user response:

You cannot deploy Firebase Cloud Functions to any other provider. Other environments might be totally different and may not have all the credentials/env variables required.

If you want to listen for realtime updates outside of GCP, you can try using Firestore's onSnapshot() but you'll need a server that runs always. The listener will stop once you serverless functions terminates.

  • Related