【发布时间】:2020-11-09 06:26:33
【问题描述】:
我每晚都使用下面的代码删除所有旧数据。
每个功能都可以正常工作,如果我创建多个计划任务,每个功能一个,它也可以正常工作。但是,当我将它们组合成一个名为 scheduleCleanData 的计划任务时,我收到 错误:无法加载默认凭据。浏览至https://cloud.google.com/docs/authentication/getting-started 了解更多信息。 在 GoogleAuth.getApplicationDefaultAsync (/workspace/node_modules/google-auth-library/build/src/auth/googleauth.js:161:19) 在 process._tickCallback (internal/process/next_tick.js:68:7)
根据this post,我相信这是由于函数没有等待回调,而不是凭据问题。但是,添加 async 或 await 关键字会导致解析错误。其中一些集合需要删除数千条记录。
任何帮助如何修改此代码以正确等待将不胜感激!
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const client = require('firebase-tools');
admin.initializeApp(functions.config().firebase)
const db = admin.firestore();
const runtimeOpts = {
timeoutSeconds: 300,
memory: '1GB'
}
exports.scheduledCleanData = functions
.runWith(runtimeOpts)
.pubsub.schedule('0 3 * * *')
.timeZone('America/Chicago')
.onRun((context) => {
return cleanOldAssignments()
.then(cleanOldDuties())
.then(cleanOldEvents())
.then(console.info("scheduledCleanData Complete!"));
});
function cleanOldAssignments() {
const dateYesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000)); // 24 hours
return db.collectionGroup('assignments').where('date', '<', dateYesterday).get()
.then(querySnapshot => {
console.info("Old assignments to remove: " + querySnapshot.size);
const promises = [];
querySnapshot.forEach(doc => {
promises.push(doc.ref.delete());
});
return Promise.all(promises);
});
}
function cleanOldDuties() {
const dateYesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000)); // 24 hours
return db.collectionGroup('duties').where('date', '<', dateYesterday).get()
.then(querySnapshot => {
console.info("Old duties to remove: " + querySnapshot.size);
const promises = [];
querySnapshot.forEach(doc => {
promises.push(doc.ref.delete());
});
return Promise.all(promises);
});
}
function cleanOldEvents() {
const dateYesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000)); // 24 hours
return db.collectionGroup('events').where('date', '<', dateYesterday).get()
.then(querySnapshot => {
console.info("Old events to remove: " + querySnapshot.size);
const promises = [];
querySnapshot.forEach(doc => {
promises.push(doc.ref.delete());
});
return Promise.all(promises);
});
}
【问题讨论】:
标签: node.js firebase google-cloud-firestore promise google-cloud-functions