我正在尝试在Google的Cloud Functions中创建一个发布/订阅函数,该函数将自动删除Firestore数据库中一天之内的所有乐谱。
这就是我的 index.js:
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* @param {!Object} event Event payload.
* @param {!Object} context Metadata for the event.
*/
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.helloPubSub = (event, context) => {
const pubsubMessage = event.data;
console.log(Buffer.from(pubsubMessage, 'base64').toString());
function deleteCollection(db, collectionPath, batchSize) {
// let collectionRef = db.collection(collectionPath);
// let query = collectionRef.orderBy('__name__').limit(batchSize);
const daysAgo = new Date();
daysAgo.setHours(daysAgo.getHours() - 24);
console.log(daysAgo);
let citiesRef = db.collection('leaderboards');
let query = citiesRef.doc('United States').collection('Daily')
.where('timestamp', '>', daysAgo)
.get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});
return new Promise((resolve, reject) => {
deleteQueryBatch(db, query, batchSize, resolve, reject);
});
}
function deleteQueryBatch(db, query, batchSize, resolve, reject) {
query.get()
.then((snapshot) => {
// When there are no documents left, we are done
if (snapshot.size === 0) {
return 0;
}
// Delete documents in a batch
let batch = db.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
return batch.commit().then(() => {
return snapshot.size;
});
}).then((numDeleted) => {
if (numDeleted === 0) {
resolve();
return;
}
// Recurse on the next process tick, to avoid
// exploding the stack.
process.nextTick(() => {
deleteQueryBatch(db, query, batchSize, resolve, reject);
});
})
.catch(reject);
}
};
这是我的 package.json中的内容:
{
"name": "sample-pubsub",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"firebase-admin": "^8.6.0",
"firebase-functions": "^3.2.0",
"@google-cloud/pubsub": "^1.1.1"
},
"keywords": [],
"author": "Code_31",
"license": "ISC"
}
当我尝试“测试功能”时,收到错误:
Error: function execution failed. Details: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
我是Cloud Functions和Node.js的新手,因此非常感谢我做错的任何帮助。谢谢!