如何为每个集合插入添加时间戳,在 Cloud Functions 中更新 Firestore 数据库 [英] How to add timestamp to every collection insert,update in Cloud Functions for firestore database

本文介绍了如何为每个集合插入添加时间戳,在 Cloud Functions 中更新 Firestore 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Posts 的 firestore 集合我在客户端做了一个插入,它可以工作.

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

我想使用 firebase 函数将 createdAt 和 updatedAt 字段添加到我的帖子集合 firestore 中的每个插入中.

I want to add the createdAt and updatedAt fields to every insert in my posts collection firestore using firebase functions.

推荐答案

UPDATE 1/31/21 - 虽然我相信我的包是很棒的代码并回答了这个问题,但有一种更便宜的方法这样做:firestore 规则:

UPDATE 1/31/21 - While I believe my package is great code and answers the question, there is a cheaper way of doing this: firestore rules:

allow create: if request.time == request.resource.data.createdAt;
allow update: if request.time == request.resource.data.updatedAt;

如果updatedAtcreatedAt 没有以正确的日期和时间添加到前端,则不允许更新/创建.这要便宜得多,因为它不需要数据函数,也不需要每次更新时额外写入.

If the updatedAt or createdAt are not added on the front end with the correct date and time, it will not allow the update / create. This is much cheaper as it does not require a function for data, nor an extra write everytime you update something.

不要使用常规的日期字段,一定要通过以下方式在前端添加时间戳:

Do not use a regular date field, be sure to add the timestamp on the frontend via:

firebase.firestore.FieldValue.serverTimestamp;


UPDATE 11/24/20 - 我实际上将以下函数放入我的 npm 包 adv-firestore-functions:


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

查看我的博客文章:https://fireblog.io/post/AhEld80Vf0FOn2t8MlZG/自动firestore-timestamps

我创建了一个通用的云函数来使用 createdAt 和 updatedAt 时间戳更新您想要的任何文档:

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;
    });


这篇关于如何为每个集合插入添加时间戳,在 Cloud Functions 中更新 Firestore 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆