繁体   English   中英

谷歌云 Function 删除 Firestore 文件

[英]Google Cloud Function delete Firestore document

我在本地模拟器上测试了我的 javascript。 有 2 个操作,如果时间戳超过 7 天,则删除文档(这就像一个魅力 <3),但除此之外,他应该检查“img”是否正常 url 如果返回 404,则像第一个操作一样删除,这仅适用于本地模拟器,当我将其部署到云 function 时,它不再工作,只是说例如“函数执行耗时 7957 毫秒,完成状态:‘ok’”,但在本地它按预期工作。

exports.removeExpiredDocuments = functions.region('europe-west1').runWith({ memory: "256MB" }).pubsub.schedule("every 1 hours").onRun(async (context) => {
    const db = admin.firestore();
    const now = firestore.Timestamp.now();
    const ts = firestore.Timestamp.fromMillis(now.toMillis() - 604800000); // 168 hours in milliseconds = 604800000

    const snaps = await db.collection("products").get();
    let promises = [];
    snaps.forEach((snap) => {
        // functions.logger.info("forEachSnap");
        if (snap.data().created_time < ts) {
            promises.push(snap.ref.delete());
            functions.logger.info('[Time] older than 7 Days ' + snap.data().name, { structuredData: true });
        } else {
            requesth(snap.data().img, function (error, response) {
                functions.logger.info('[img] error: ' + error, { structuredData: true });
                if (response.statusCode == 404) {
                    promises.push(snap.ref.delete());
                    functions.logger.info('[img] not found ' + snap.data().name, { structuredData: true });
                }
            });
        }
    });

    return Promise.all(promises);
});

在本地模拟器上工作(与在 firebase 中使用相同的 url),我希望它也能在云上工作

firestore.Timestamp.now()不会返回可以通过 < 和 > 比较与其他时间戳正确比较的值。 这意味着这行代码并没有按照您的想法进行:

if (snap.data().created_time < ts)

如果要将两个Timestamp对象相互比较,则必须采用另一种方法。 一种方法是使用toMillis()将它们都转换为毫秒,并将这些整数相互比较。 或者将它们转换为 Date 并将它们与适当的 object 方法进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM