【发布时间】:2021-02-04 15:53:02
【问题描述】:
我一直在尝试找到一种方法,在我的案例 24 小时后,可以在一定时间后删除 firestore 中的集合中的文档,为此我意识到我必须使用 firebase 云功能,所以在调查后我找到了这个post,它完成了我需要在我的项目中添加的工作,除了我使用的是打字稿而不是那个问题中使用的javascript,我无法将其更改为javascript,因为我已经在使用typecipt发送通知给用户。如何将以下代码更改为 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);
});
});
这是需要在 24 小时后删除的数据的图像,created 字段是创建文档的日期,deleted id 是应该删除文档的日期。
编辑: 我发现问题不是因为使用了打字稿,而是因为我使用的是 firestore 而不是 firebase 实时数据库,所以我创建了这段代码,它应该可以让事情正常工作,但它没有.我该如何解决这个问题?
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;
});
【问题讨论】:
-
任何有效的 JavaScript 都是自动有效的 TypeScript,在那里不需要转换。但是您共享的代码是用于 Firebase 实时数据库(我应该知道,正如我所写的那样),而您正在使用 Cloud Firestore。您需要调整它以适应该数据库的 API。
-
@FrankvanPuffelen 谢谢你,我没有注意到,我会尝试调整它,如果它有效,我会发布答案。
标签: node.js typescript firebase google-cloud-firestore google-cloud-functions