How to add timestamp to every collection insert,update in Cloud Functions for firestore database

后端 未结 6 522
心在旅途
心在旅途 2020-11-29 09:23

I have a firestore collection called Posts I make an insert on the client side and it works.

I want to add the createdAt and updatedAt fields to every insert in my p

6条回答
  •  佛祖请我去吃肉
    2020-11-29 10:08

    UPDATE 11/24/20 - I actually put the below function in my npm package adv-firestore-functions:

    See: https://fireblog.io/blog/post/automatic-firestore-timestamps


    I created a universal cloud function to update whatever documents you want with the createdAt and updatedAt timestamp:

    exports.myFunction = functions.firestore
        .document('{colId}/{docId}')
        .onWrite(async (change, context) => {
    
            // the collections you want to trigger
            const setCols = ['posts', 'reviews','comments'];
    
            // if not one of the set columns
            if (setCols.indexOf(context.params.colId) === -1) {
                return null;
            }
    
            // simplify event types
            const createDoc = change.after.exists && !change.before.exists;
            const updateDoc = change.before.exists && change.after.exists;
            const deleteDoc = change.before.exists && !change.after.exists;
    
            if (deleteDoc) {
                return null;
            }
            // simplify input data
            const after: any = change.after.exists ? change.after.data() : null;
            const before: any = change.before.exists ? change.before.data() : null;
    
            // prevent update loops from triggers
            const canUpdate = () => {
                // if update trigger
                if (before.updatedAt && after.updatedAt) {
                    if (after.updatedAt._seconds !== before.updatedAt._seconds) {
                        return false;
                    }
                }
                // if create trigger
                if (!before.createdAt && after.createdAt) {
                    return false;
                }
                return true;
            }
    
            // add createdAt
            if (createDoc) {
                return change.after.ref.set({
                    createdAt: admin.firestore.FieldValue.serverTimestamp()
                }, { merge: true })
                    .catch((e: any) => {
                        console.log(e);
                        return false;
                    });
            }
            // add updatedAt
            if (updateDoc && canUpdate()) {
                return change.after.ref.set({
                    updatedAt: admin.firestore.FieldValue.serverTimestamp()
                }, { merge: true })
                    .catch((e: any) => {
                        console.log(e);
                        return false;
                    });
            }
            return null;
        });
    
    
    

提交回复
热议问题